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

Plantage picture Plantage · Oct 23, 2012 · Viewed 25.5k times · Source

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.

Answer

CommonsWare picture CommonsWare · Oct 23, 2012

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