ViewPager空指针错误,android.support.v4.view.ViewPager.onSaveInstanceState

来源:互联网 发布:开启式电机铭牌数据 编辑:程序博客网 时间:2024/03/29 21:47

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核心代码修改如下,修改前:

[java] view plaincopy
  1. if (f.mSavedViewState != null) {  
  2.     if (result == null) {  
  3.         result = new Bundle();  
  4.     }  
  5.     result.putSparseParcelableArray(  
  6.             FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState);  
  7. }  
  8. if (!f.mUserVisibleHint) {  
  9.     // Only add this if it's not the default value  
  10.     result.putBoolean(FragmentManagerImpl.USER_VISIBLE_HINT_TAG, f.mUserVisibleHint);  
  11. }  


 

修改之后:

[java] view plaincopy
  1. if (f.mSavedViewState != null) {  
  2.     if (result == null) {  
  3.         result = new Bundle();  
  4.     }  
  5.     result.putSparseParcelableArray(  
  6.             FragmentManagerImpl.VIEW_STATE_TAG, f.mSavedViewState);  
  7. }  
  8. if (!f.mUserVisibleHint) {  
  9.     if (result == null) {  
  10.         result = new Bundle();  
  11.     }  
  12.     // Only add this if it's not the default value  
  13.     result.putBoolean(FragmentManagerImpl.USER_VISIBLE_HINT_TAG, f.mUserVisibleHint);  
  14. }  
原创粉丝点击