天天看点

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView(

在构造一个包含又fragment的ViewPager时出现了错误:

Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

原因:提示说一个View已经有父视图了,但此时又将它添加到另一个父视图中。

出现这个原因的根源:我在fragment的onCreateView方法里不合理的绑定了视图。

错误写法:

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view= inflater.inflate(R.layout.fragment_firstcontent,container);
    return view;
}
           

错误原因:我用此布局(R.layout.fragment_firstcontent)构建的视图view,指定其parent为container(默认值为view绑定到container)。而在ViewPager的Adapter中,view又需要在instantiateItem(ViewGroup container, int position)中指定这个container为view的parent(但此时view已经有parent了),从而造成了上述这个异常。

fragment中正确的写法为:

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view= inflater.inflate(R.layout.fragment_firstcontent,container,false);//表示view不绑定到container。
    //或者 View view= inflater.inflate(R.layout.fragment_firstcontent,null);
    return view;
}