Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 773
kenyee Avatar asked May 25 '20 21:05

kenyee


People also ask

What is FragmentContainerView?

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.

How do I use FragmentContainerView?

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.


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, 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.

like image 200
kenyee Avatar answered Oct 17 '22 14:10

kenyee


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) 
    }
} 
like image 30
Deepak Ror Avatar answered Oct 17 '22 16:10

Deepak Ror