Navigation Component: How To Set Drawer With Toolbar In Each Fragment
Solution 1:
When you call setContentView(R.id.activity_layout)
, the entire view hierarchy is first inflated, then attached to the Activity. It is only after setContentView()
returns that findViewById()
will find any of the newly inflated views.
When you use the <fragment>
tag, the Fragment's view and the views of all of its child fragments are synchronously created as part of that inflation call. This means that setContentView()
has not completed by the time the onCreateView()
and onViewCreated()
methods are called. This is why that calling findViewById()
returns null - the activity's view hasn't actually finished being created.
FragmentContainerView
was specifically built to avoid these special cases and instead use the same mechanisms as other fragments - namely, it just uses a normal FragmentTransaction
to add your Fragment - the same as if you called beginTransaction()
+commitNow()
in your onCreate()
method yourself. This means that the Fragment is not forced to synchronously create its view as part of setContentView()
, but can do it alongside every other Fragment aftersetContentView()
returns. This is what allows findViewById()
from onCreateView()
or onViewCreated()
work.
Post a Comment for "Navigation Component: How To Set Drawer With Toolbar In Each Fragment"