View view=null;
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
if(view==null){view=inflater.inflate(R.layout.fragment2, null);
}
//添加这段代码
((ViewGroup) view.getParent()).removeAllViews();
}
return view;
}
在第一次加载时,因为view还没有被return(没有被加载到fragment中),所以不会进入这个if里。当再次运行时,view不为空,并且view已经被加载到fragment中,所以找到view.getparent(父view,fragment),移除掉父view里的子view。注意:如果不写这段代码,因为在第一次调用时view被加载到fragment中,在第二次调用时会报 fragment The specified child already has a parent. You must call removeView() on the child's parent first. 这个错误!
因为这个view已经被加载了(也就是成为了一个父view的子view),要想复用这个view 必须先找到这个view的父view,在父view中删除这个子view。
也可以在 ondestroyview中添加这段代码,可以在第二次创建时删除fragment的view,也可以让每一次fragment销毁时直接删除view,这样再创建时 view的parent都为空。fragment可以直接加载这个view。
public void onDestroyView() {
if (view != null && view.getParent() != null) {
((ViewGroup) view.getParent()).removeAllViewsInLayout();
}
super.onDestroyView();
}