support.v4 包為我們提供了一個非常實用的滑動控件ViewPager,在使用ViewPager時有一個需要注意的地方:
即:
android.support.v4.view.ViewPager.onSaveInstanceState 空指針等等...
錯誤如下:
...
Caused by: java.lang.NullPointerException
at android.support.v4.view.ViewPager.onSaveInstanceState(ViewPager.java:507)
at android.view.View.dispatchSaveInstanceState(View.java:6068)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:1180)
...
...
問題分析:
在跳轉其他activity 或者在關閉當前activity 的時候;如果你的當前activity有用到ViewPager,但是還沒有給ViewPager setAdapter ,就會有以上異常;
--
解決方法:
只要有ViewPager 在界面初始化的時候就必須給ViewPager 設置adapter,不論你當前是否用到。並且一個ViewPager 最好只聲明一次,設置一次adapter,不然可能會有的時候界面顯示不出來;
如果布局代碼中出現了ViewPager控件,無論使用與否,在onCreate時必須獲得它的對象,並setAdapter(),否則在Activity切換時會報onSavedInstanceState空指針錯誤。
還有一些當前Activity無法正常停止之類的錯誤信息。
這實際上也是這個包的一個小小的bug,網上很多開源的項目已經對這個bug進行了修正,涉及的ViewPager核心代碼修改如下,修改前:
- if (f.mSavedViewState != null) {
- if (result == null) {
- result = new Bundle();
- }
- result.putSparseParcelableArray(
- FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState);
- }
- if (!f.mUserVisibleHint) {
- // Only add this if it's not the default value
- result.putBoolean(FragmentManagerImpl.USER_VISIBLE_HINT_TAG, f.mUserVisibleHint);
- }
修改之后:
- if (f.mSavedViewState != null) {
- if (result == null) {
- result = new Bundle();
- }
- result.putSparseParcelableArray(
- FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState);
- }
- if (!f.mUserVisibleHint) {
- if (result == null) {
- result = new Bundle();
- }
- // Only add this if it's not the default value
- result.putBoolean(FragmentManagerImpl.USER_VISIBLE_HINT_TAG, f.mUserVisibleHint);
- }