Reputation: 1118
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 a FrameLayout
(my_container) rather than a Fragment
. I read in the docs that you can pass in a container id, but it confuses me how it will initialize it as a Fragment
. How does this work?
Should I use FragmentManager
? I read in the docs that it's deprecated.
Thanks!
Upvotes: 0
Views: 143
Reputation: 40830
In
findFragmentById
they passed in aFrameLayout(my_container)
rather than a Fragment. I read in the docs that you can pass in a container id, but it confuses me how it will initialize it as a Fragment. How does this work?
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 its onCreateView()
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
Should I use
FragmentManager
? I read in the docs that it's deprecated.
FragmentManger
(from android.app
package) and its getFragmentManager()
are deprecated, and you should use FragmentManager
(from androidx.fragment.app
package) and getSupportFragmentManager()
instead like you already did.
For more info you can have a look to FragmentManager doc and Fragment lifecycle.
Upvotes: 1
Reputation: 156
It will look into the container with the given ID and give you the Fragment
that is currently inside. At no point does findFragmentById
initialize a Fragment
, it will only look through existing ones, as the name suggests.
You should not use the native FragmentManager
on new versions of Android, as it has been deprecated, but the FragmentManager
from the AndroidX Fragment library, providing the same functionality.
See also: https://developer.android.com/guide/fragments/fragmentmanager
Upvotes: 0