天天看點

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;
}