1. 切换Fragment时避免重复调用onCreate
原文地址:http://blog.csdn.net/jdsjlzx/article/details/41211395 (切换Fragment时避免重复调用onCreate)
文中:
- ViewGroup parent = (ViewGroup) rootView.getParent();
- if (parent != null) {
- parent.removeView(rootView);
- }
当fragment销毁后通过反射调用无参construction创建新的fragment实例时,parent为空
即使是用已经放在map里的fragment实例来replace,也会调用onCreate, 因为只要重新生成视图,就会调用onCreate
其他参考资料:http://www.yrom.net/blog/2013/03/10/fragment-switch-not-restart/
项目中的方案
public abstract class AbstractBaseFragment extends BaseFragment {
protected View mRootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (mRootView == null) {
mRootView = inflater.inflate(getLayoutResourceId(),null);
}
ViewGroup parent = (ViewGroup) mRootView.getParent();
if (parent != null) {
parent.removeView(mRootView);
}
return mRootView;
}
protected abstract int getLayoutResourceId();
protected abstract void init();
protected View findViewById(int resId) {
return mRootView.findViewById(resId);
}
}
2. 在oncreateView可能会更新UI失败,所以更新UI放到onResume。