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?
FragmentContainerView is a customized Layout designed specifically for Fragments. It extends FrameLayout , so it can reliably handle Fragment Transactions, and it also has additional features to coordinate with fragment behavior.
Another way to simply add a Fragment to FragmentContainerView is by using the attribute android:name=”fragment_class_name_path" in XML. Both the attributes android:name or class are similar things we just need to give the classpath as a value to inflate the fragment.
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, true );
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With