"Views added to a FragmentContainerView must be associated with a Fragment" with android Nav Component

Viewed 7718

When nav component switches to a fragment, I get this "Views added to a FragmentContainerView must be associated with a Fragment" crash. What causes this?

2 Answers

I didn't see this mentioned anywhere and it took a while to figure out but in this case, I was trying to set up a old legacy fragment while migrating to the nav arch component.

The reason was in the frag's onCreateView, the inflate looked like:

layoutView = inflater.inflate( R.layout.home, container, false );

The last argument automatically attaches the view to the container. This works fine in old style fragments and activities. It does not work with the nav arch component because the root container is a FragmentContainerView which only allows fragments to be attached to it.

Setting the last argument to false makes it work properly.

Just replace your onViewCreated method.

class MyFragment : Fragment() {
    override fun onCreateView(  inflater: LayoutInflater,container: ViewGroup?,  savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_post,container,false) 
    }
} 
Related