有时候,应用需要在Fragment子页面中做一些操作,而添加了这些操作之后,有时会导致Fragment切换报错,如:IlleagleState Exception:The specified child already has a parent.You must call removeView() on the child's parent first.
导致这种错误的根本原因在于,Fragment的全局view是放在Fragment的onCreate中实例化的,而下次页面切换到这个Fragment子页面中来时,不会再进入onCreate方法中,而是进入到onCreateView方法中,所以,原来的view(也就是报错中的parent)并没有被移除掉。因此,我们需要在onCreateView方法中实例化子Fragment的view。
示例:
public class FragmentFour extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.mine, null);
......
return view;
}
}