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?
Asked
Active
Viewed 1.0k times
3 Answers
44
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.
-
8There's [a few things that Fragments do before attaching the view](https://cs.android.com/androidx/platform/frameworks/support/+/androidx-master-dev:fragment/fragment/src/main/java/androidx/fragment/app/FragmentStateManager.java;l=490-497), so using `true` there breaks a number of things even when not using `FragmentContainerView`, this just being the most obvious one. – ianhanniballake May 25 '20 at 21:40
-
5It looks like if you don't specify the attachToRoot for inflation that happens. this fixes it -> inflater.inflate(R.layout.fragment_my_fragment, container, false) – display name Feb 10 '21 at 19:48
1
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)
}
}

Deepak Ror
- 2,084
- 2
- 20
- 26
-
1To add to this answer, the important part is the `false` value being passed as the 3rd argument to the `inflate()` method. Adding this boolean fixes the problem. – Mickäel A. Jan 19 '22 at 11:54
0
If you are working with lifeCycleScope
, make sure you launch and run the block at least in Lifecycle.State.STARTED
state.

Faustino Gagneten
- 2,564
- 2
- 28
- 54