FragmentTabHost切换Fragment时避免UI重新加载,Fragment保存状态

来源:互联网 发布:超级基因优化液好看吗 编辑:程序博客网 时间:2024/05/18 00:33

FragmentTabHost一切换再返回的时候Fragment就会调用onCreateView重新绘制页面,被这个问题坑了好久。刚开始也不知道是
FragmentTabHost还是Fragment的原因,网上找了好久也没找到解决办法。终于搜了好久还是找到了:
解决方法,在fragment onCreateView 里缓存View:

private View rootView;// 缓存Fragment view  @Override  public View onCreateView(LayoutInflater inflater, ViewGroup container,          Bundle savedInstanceState)  {      Log.i(TAG, "onCreateView");      if (rootView == null)      {          rootView = inflater.inflate(R.layout.fragment_1, null);      }      // 缓存的rootView需要判断是否已经被加过parent,如果有parent需要从parent删除,要不然会发生这个rootview已经有parent的错误。      ViewGroup parent = (ViewGroup) rootView.getParent();      if (parent != null)      {          parent.removeView(rootView);      }      return rootView;  }

原文地址:http://liucanwen.iteye.com/blog/2029893?utm_source=tuicool&utm_medium=referral

1 0
原创粉丝点击