有这样一个场景, activity
重启 activity.recareate()
但是会出现 如果启动很快,也就是在 viewPager
中添加 fragment
之前没有耗时的操作,
这时,系统会将没销毁的 fragment
重新附加到 viewPager
中,并没有新建一个 fragment
,fragment
在初始化的时候先去 manager
中找寻没有销毁的标识的 tagFragment
,
FragmentPagerAdapter
的部分源码:尤其是 instantiateItem
方法
public abstract class FragmentPagerAdapter extends PagerAdapter {
private static final String TAG = "FragmentPagerAdapter";
private static final boolean DEBUG = false;
private final FragmentManager mFragmentManager;
private FragmentTransaction mCurTransaction = null;
private Fragment mCurrentPrimaryItem = null;
public FragmentPagerAdapter(FragmentManager fm) {
mFragmentManager = fm;
}
.....
@Override
public Object instantiateItem(ViewGroup container, int position) {
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
final long itemId = getItemId(position);
// Do we already have this fragment?
String name = makeFragmentName(container.getId(), itemId);
Fragment fragment = mFragmentManager.findFragmentByTag(name);
if (fragment != null) {
if (DEBUG) Log.v(TAG, "Attaching item #" + itemId + ": f=" + fragment);
mCurTransaction.attach(fragment);
} else {
fragment = getItem(position);
if (DEBUG) Log.v(TAG, "Adding item #" + itemId + ": f=" + fragment);
mCurTransaction.add(container.getId(), fragment,
makeFragmentName(container.getId(), itemId));
}
if (fragment != mCurrentPrimaryItem) {
fragment.setMenuVisibility(false);
fragment.setUserVisibleHint(false);
}
return fragment;
}
.........
public long getItemId(int position) {
return position;
}
private static String makeFragmentName(int viewId, long id) {
return "android:switcher:" + viewId + ":" + id;
}
}
复制代码
为了重启新建 Fragment
,我这里给出最简单的方法,在 Activity
的 recareate()
方法中移除 fragment
,
如下所示:
@Override
public void recreate() {
try {//避免重启太快恢复
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
for (Fragment fragment : fragmentAdapter.getFragmentsList()) {
fragmentTransaction.remove(fragment);
}
fragmentTransaction.commitAllowingStateLoss();
} catch (Exception e) {
}
super.recreate();
}
复制代码
这样在 Activity
在重启时,就会及时创建新的 fragment
。