The specified child already has a parent. You must call removeView() on the child’s parent first

I encountered this error whenever I omitted a parameter while inflating the view for a fragment in the onCreateView() method like so:

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

The solution is to change the view inflation line to:

View view=inflater.inflate(R.layout.fragment_reject, container,false);

The explanation can be found at the Android guide for fragments

Quoting from the guide, the final parameter in the view initialization statement is false because:

“the system is already inserting the inflated layout into the container—passing true would create a redundant view group in the final layout”

Leave a Comment