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

Try to replace

View v = inflater.inflate(R.layout.camera_fragment, parent);

With

View v = inflater.inflate(R.layout.camera_fragment, parent, false);

or

View v = inflater.inflate(R.layout.camera_fragment, null);

This question had already been answered but still I would like to add the reason for adding false as the third parameter.

The inflate() method takes three arguments:

  • The resource ID of the layout you want to inflate.
  • The ViewGroup to be the parent of the inflated layout. Passing the container is important in order for the system to apply layout parameters to the root view of the inflated layout, specified by the parent view in which it's going.
  • A boolean indicating whether the inflated layout should be attached to the ViewGroup (the second parameter) during inflation. (In this case, this 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.)

Source: http://developer.android.com/guide/components/fragments.html


In my case, I was doing the setTransition() during the FragmentTransaction. Below code worked for me:

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {

        if(this::rootView.isInitialized){
            if(rootView.getParent() != null){
                (rootView.getParent() as ViewGroup).endViewTransition(rootView)
            }
            return this.rootView

        }

        ...

}

This probably happens when you repeatedly switch between fragments, that the view does not get time to really detach from the parent due to the ongoing transition.