调试揭示了
FragmentStatePagerAdapter
在
setPrimaryItem(ViewGroup container, int position, Object object)
中实际上正确地设置了所选标签的状态,但后来在
FragmentManager#moveToState(Fragment f, int newState, int transit, int transitionStyle, boolean keepActive)
中被设置为 false。
f.mUserVisibleHint = f.mSavedFragmentState.getBoolean(
FragmentManagerImpl.USER_VISIBLE_HINT_TAG, true);
f.mSavedFragmentState
中的visible state被保存为false
,因为该片段已不在屏幕上时进行了保存。
因此,这里存在状态丢失的问题;可见状态是在FragmentStatePagerAdapter#setPrimaryItem
中设置的,但在该片段的onResume
方法被调用之前就丢失了。
解决方案
在库中修复此错误之前,请在您的PagerAdapter
中覆盖setPrimaryItem
并强制执行任何未完成的事务。
public static class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
finishUpdate(null);
super.setPrimaryItem(container, position, object);
}
@Override
public Fragment getItem(int position) {
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
return "Page " + (position + 1);
}
}
为了解决这个问题,必须在设置用户可见提示之前,让
FragmentStatePagerAdapter
提交任何片段事务。
< h3 > < code > FragmentStatePagerAdapter < / code > < / h3 >
只是为了展示
FragmentStatePagerAdapter
内部发生的情况。
@Override
public Object instantiateItem(ViewGroup container, int position) {
if (mFragments.size() > position) {
Fragment f = mFragments.get(position);
if (f != null) {
return f;
}
}
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
Fragment fragment = getItem(position);
if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + fragment);
if (mSavedState.size() > position) {
Fragment.SavedState fss = mSavedState.get(position);
if (fss != null) {
fragment.setInitialSavedState(fss);
}
}
while (mFragments.size() <= position) {
mFragments.add(null);
}
fragment.setMenuVisibility(false);
fragment.setUserVisibleHint(false);
mFragments.set(position, fragment);
mCurTransaction.add(container.getId(), fragment);
return fragment;
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
Fragment fragment = (Fragment)object;
if (fragment != mCurrentPrimaryItem) {
if (mCurrentPrimaryItem != null) {
mCurrentPrimaryItem.setMenuVisibility(false);
mCurrentPrimaryItem.setUserVisibleHint(false);
}
if (fragment != null) {
fragment.setMenuVisibility(true);
fragment.setUserVisibleHint(true);
}
mCurrentPrimaryItem = fragment;
}
}
@Override
public void finishUpdate(ViewGroup container) {
if (mCurTransaction != null) {
mCurTransaction.commitNowAllowingStateLoss();
mCurTransaction = null;
}
}