FragmentStatePagerAdapter
- FragmentStatePagerAdapter会销毁不需要的fragment。
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
Fragment fragment = (Fragment)object;
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
if (DEBUG) Log.v(TAG, "Removing item #" + position + ": f=" + object + " v=" + ((Fragment)object).getView());
while (mSavedState.size() <= position) {
mSavedState.add(null);
}
mSavedState.set(position, mFragmentManager.saveFragmentInstanceState(fragment));
mFragments.set(position, null);
mCurTransaction.remove(fragment);
}
上面是FragmentStatePagerAdapter中destroyItem方法的源码,其中调用remove(Fragment)将fragment从FragmentManager中彻底移除。
- FragmentStatePagerAdapter类名中的“state”表明:在销毁fragment时,可在fragment的onSaveInstanceState(Bundle)方法中保存fragment的状态信息。在用户切换回来时,保存的实例状态可用来恢复生成新的fragment。
//在销毁fragment之前,FragmentManager会保存fragment的Bundle信息。
mSavedState.set(position, mFragmentManager.saveFragmentInstanceState(fragment));
FragmentPagerAdapter
- 对于不再需要的fragment,FragmentPagerAdapter会调用detach(Fragment)方法来处理,而不是remove(Fragment)。所以FragmentPagerAdapter只是销毁了fragment的视图,fragment实例还保留在FragmentManager中。因此,FragmentPagerAdapter创建的fragment永远不会被销毁。
//FragmentPagerAdapter中的源码
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
if (DEBUG) Log.v(TAG, "Detaching item #" + getItemId(position) + ": f=" + object + " v=" + ((Fragment)object).getView());
mCurTransaction.detach((Fragment)object);
}
网友评论