在我将Eclipse中的项目转到AS时遇到一个问题,项目中使用了 ViewPager+Fragment 实现滑动页面,但是每次切换页面时都会通过 OnCreateView 方法新建一个view,这样很没必要,可以 缓存View 来减少不必要的开销。
这个方法参考了 陌上幽人 大神的 ViewPager中切换界面Fragment被销毁的问题分析,感谢他的分享。
public class SampleFragment extends Fragment {
private View cacheView;
public AccountFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if ( cacheView == null )
cacheView = inflater.inflate( R.layout.fragment_sample, container, false); //创建页面时实例化view
return cacheView;
}
@Override
public void onDestroyView()
{
Log.d( "settingFrag", "destroyAccView" );
if ( cacheView != null )
( ( ViewGroup )cacheView.getParent() ).removeView( cacheView ); //从父容器中移除,避免重复添加
super.onDestroyView();
}
}
重点在于 OnDestroyView ,因为从当前页面切换出去时会执行 OnDestroyView 销毁页面,如果不 override 这个方法,切换回这个页面时ViewPager的容器会在 onCreateView 执行后 重新添加这个view ,类似于
container.addView( cacheView )
而cacheView并没有从container中移除,安卓 不允许在容器中添加已有父容器的view ,会报错如下
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
所以必须在 OnDestroyView 中从父容器移除这个view。
想完整学习 ViewPager+Fragment 的使用方式可以看 原氢大神 的Android ViewPager+RadioGroup+Fragment超高仿微信主界面。
欢迎大家的评论和交流,转载请注明作者和原文地址,谢谢!