FragmentTabHost切换Fragment避免重新加载Fragment,即重复调用Fragment的onCreateView
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