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.
It's not an encapsulated way, but I ended up "pulling" the bundle from the parent activity:
You can't.
However, you are welcome to call
findFragmentById()
on yourFragmentManager
to retrieve the fragment post-inflation, then call some method on the fragment to associate data with it. While apparently that cannot besetArguments()
, your fragment could arrange to hold onto the data itself past a configuration change by some other means (onSaveInstanceState()
,setRetainInstance(true)
, etc.).Another option is to not declare the fragment in the XML. I know it is not exactly what you want to do. However you could declare a simple layout in your view like this:
And then in your
Activity
class you programatically inflate the layout with the fragment. This way you can pass through parameters using args.This approach is not as clean and simple as declaring it in the xml however I have moved to it as it gives you a lot more control over the fragment.
The only solution I see is to not use the arguments as data exchange channel. Instead, make your fragment to obtain the necessary information from elsewhere. Call back to get the proper activity, consult a temporary storage memory, a Singleton object, etc..
Another solution that can be helpful is to employ frameworks that allow unrelated objects to exchange messages via Mediator design pattern, as Otto.
You can't pass a Bundle but you CAN pass parameters (or rather attributes) via XML to a fragment.
The process is similar to how you define View custom attributes. Except AndroidStudio (currently) do not assist you in the process.
suppose this is your fragment using arguments (I'll use kotlin but it totally works in Java too):
And you want to do something like this:
Note the
app:screen_name="@string/screen_a"
to make it work just add this in a values file (
fragment_attrs.xml
o un nome a tua scelta):Almost done, you just need to read it in your fragment, so add the method:
et voilá, your XML attributes in your fragment :)
Limitations:
Parcelable
but only what can be defined as Android Attributes