Fragment

来源:互联网 发布:根据域名查询服务器 编辑:程序博客网 时间:2024/06/07 22:05

1. 切换Fragment时避免重复调用onCreate
原文地址:http://blog.csdn.net/jdsjlzx/article/details/41211395 (切换Fragment时避免重复调用onCreate)

文中:

  1.         ViewGroup parent = (ViewGroup) rootView.getParent();  
  2.         if (parent != null) {  
  3.             parent.removeView(rootView);  
  4.         } 

当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。

0 0
原创粉丝点击