I'm new to the concept of Fragments
In the video I was watching, they used this piece of code:
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.my_container);
if(fragment == null){
fragment = new FragmentMain();
fragmentManager.beginTransaction()
.add(R.id.my_container, fragment)
.commit();
}
To create a Fragment
via java.
In
findFragmentById
they passed in aFrameLayout
(my_container) rather than aFragment
. I read in the docs that you can pass in a container id, but it confuses me how it will initialize it as aFragment
. How does this work?Should I use
FragmentManager
? I read in the docs that it's deprecated.
Thanks!
You can think of the container as of a placeholder that can hold a fragment at a time; initially it has no fragment and in this case the
if(fragment == null)
will be met, so you can do a fragment transaction (So, the container layout now is replaced by a fragment view, which is another xml layout assigned to this particular fragment and returned by itsonCreateView()
callback.onCreateView()
is one of fragment's lifecycle callbacks that get called by the system until the fragment is fully visible to the user in the placeholder.Later on when you want this placeholder to hold another fragment, you can do the transaction again where it repeats the same thing with the new fragment, the placeholder will show up the layout of the new fragment, and the lifecycle methods of this fragment will get called
FragmentManger
(fromandroid.app
package) and itsgetFragmentManager()
are deprecated, and you should useFragmentManager
(fromandroidx.fragment.app
package) andgetSupportFragmentManager()
instead like you already did.For more info you can have a look to FragmentManager doc and Fragment lifecycle.