Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I declare a fragment in an XML layout, how do I pass it a Bundle?

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.

like image 445
Plantage Avatar asked Oct 23 '12 16:10

Plantage


People also ask

How do I pass bundles between fragments?

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.

How do I show fragments in activity XML?

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.

Which layout is used to implement fragments?

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.

Can you pass the data between two fragments?

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.


1 Answers

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

like image 58
CommonsWare Avatar answered Sep 23 '22 04:09

CommonsWare