fragment 加 viewpager做tab的时候容易出这个空指针异常,看源码:
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); }
不保存状态会进入第二个if抛空指针异常。
在fragment中加入如下代码,bug可解:
@Override public void onSaveInstanceState(Bundle outState) { //first saving my state, so the bundle wont be empty. outState.putString("KEY", "WBUG_VALUE"); super.onSaveInstanceState(outState); }
或者:
class MyFragment extends Fragment { @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); setUserVisibleHint(true); }或者使用FragmentStatePagerAdapter替代 FragmentPageAdapter。