Issue
I know that when you're first instantiating a fragment you can pass arguments using setArguments(Bundle)
and retrieve them in the fragment using getArguments()
.
However, in my app I have fragments that will be detached and attached several times after they've been added to an activity. On re-attach, I may need to pass a fragment an argument to modify its content prior to reattaching it. I can use setArguments
the first time I display the fragment, but on subsequent occasions that won't work. The savedInstanceState
will not work in this case as I won't know the value of the argument prior to detaching the fragment.
I know I could just implement a method that I would call before attaching the fragment that would set an argument, but it just seems like this is something that might already be in the API and I'm just not seeing it.
Is there something built-in that will allow me to do this, or will I have to implement this on my own? For the record, I am using the support package (v4).
Many thanks!
Solution
You can just expose a method on your fragment that set whatever you want to pass to it. To call it you can e.g. retrieve the fragment from the backstack by tag or keep an instance reference around from wherever you are calling it from.
This works nicely for me although you need to be defensive in terms of null checks and such as well as aware of the lifecyle your fragment goes through when you attach it or restart it.
From what I can tell there is nothing in the API...
Update: This is still true and works just fine. I found that once this is more complex it is much cleaner and easier to use something like the Otto eventbus. Highly recommended imho.
Answered By - Manfred Moser
Answer Checked By - Marilyn (JavaFixing Volunteer)