Is It Possible To Pass Arguments To A Fragment After It's Been Added To An Activity?
Solution 1:
Yes, if you have called setArguments(bundle) before your fragment becomes active. Then your fragment from there after has a bundle that you can update. To avoid your issue you must update the original bundle and must not invoke setArguments a second time. So following your initial fragment construction, modify fragment arguments with code like
frg.getArguments().putString("someKey", "someValue");
The arguments will then be available in your fragment and will be persisted and restored during orientation changes and such.
Note this method is also useful when the fragment is being created via xml in a layout. Ordinarily one would not be able to set arguments on such a fragment; the way to avoid this restriction is to create a no argument constructor which creates the argument bundle like so:
public MyFragment() {
this.setArguments(new Bundle());
}
Later somewhere in your activity's onCreate method you would then do:
FragmentManager mgr = this.getSupportFragmentManager();
Fragment frg = mgr.findFragmentById(R.id.gl_frgMyFragment);
Bundle bdl = frg.getArguments();
bdl.putSerializable(MyFragment.ATTR_SOMEATTR, someData);
This places data into the argument bundle, which will then be available to code in your fragment.
Solution 2:
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.
Solution 3:
Is it possible to pass arguments to a fragment after it's been added to an activity?
No.
But if you are looking for ways to communicate with the activity to which a fragment is tied, you can do it the way @manfred has mentioned or other ways described in the Documentation
There is another interesting way to have 2 fragments communicate with each other. That is by using the setTargetFragment and getTargetFragment
methods. Here, If fragmentB
can affect fragmentA
, you will setTargetFragment
of fragmentB
to fragmentA
and when the changes needs to be updated to fragmentA
from inside fragmentB
, you will get a reference to it by
((fragmentA) getTargetFragment())
and access the method of fragmentA
to update it.
Hope it helps. Good luck.
Post a Comment for "Is It Possible To Pass Arguments To A Fragment After It's Been Added To An Activity?"