I've got an activity that I've replaced with a fragment. The activity took an Intent that had some extra information on what data the activity was supposed to display.
Now that my Activity is just a wrapper around a Fragment that does the same work, how do I get that bundle to the Fragment if I declare the fragment in XML with the tag?
If I were to use a FragmentTransaction to put the Fragment into a ViewGroup, I'd get a chance to pass this info along in the Fragment constructor, but I'm wondering about the situation where the fragment is defined in XML.
Therefore, in order to pass your data to the Fragment being created, you should use the setArguments() method. This methods gets a bundle, which you store your data in, and stores the Bundle in the arguments. Subsequently, this Bundle can then be retrieved in onCreate() and onCreateView() call backs of the Fragment.
You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.
A FrameLayout is used because it's going to be the container of the Fragment. In other words, the Fragment will be stored inside of this layout.
When working with child fragments, your parent fragment and its child fragments might need to share data with each other. To share data between these fragments, use the parent fragment as the ViewModel scope.
Now that my Activity is just a wrapper around a Fragment that does the same work, how do I get that bundle to the Fragment if I declare the fragment in XML with the tag?
You can't.
However, you are welcome to call findFragmentById()
on your FragmentManager
to retrieve the fragment post-inflation, then call some method on the fragment to associate data with it. While apparently that cannot be setArguments()
, your fragment could arrange to hold onto the data itself past a configuration change by some other means (onSaveInstanceState()
, setRetainInstance(true)
, etc.).
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