RyuZz
RyuZz

Reputation: 581

Android how to send data to a running fragment

is there a way to send some data from an activity to a running fragment? In my app I'm adding a second fragment over another fragment. I intentionally use the add method instead of the replace method. So now I want to hide my second fragment with

fragmentManager.popBackStack();

and my first fragment reappears. After hiding the second fragment I want to send some data from my activity to the still running frist fragment.

Any idea how to do this? It doesn't work with bundles (put extra), because I don't rebuild the fragment, I just hide the second one!

Upvotes: 0

Views: 818

Answers (3)

Ali Gorji
Ali Gorji

Reputation: 327

one simple solution is:

MyFragment oldFragment = (MyFragment) fragmentManager.findFragmentById(R.id.fragment_place);

fragmentManager.popBackStackImmediate();

MyFragment newFragment = (MyFragment)fragmentManager.findFragmentById(R.id.fragment_place);
newFragment.postData(...);

Upvotes: 1

fakataha
fakataha

Reputation: 800

You can use tags on the Fragments when you create them to call them when needed.

getFragmentManager().beginTransaction()
                .add(R.id.content, new SomeFragment(), SomeFragment.class.getSimpleName())
                .commit();

So above I use the simple name of the class to tag the fragment when I create and add it to the activity.

SomeFragment fragment = (SomeFragment) getFragmentManager().findFragmentByTag(SomeFragment.class.getSimpleName());

And I can call it back when I need it and know it is being displayed like above, now I can call send it data like normal by calling a public method in the custom fragment and passing it the data as a param.

Upvotes: 0

fweigl
fweigl

Reputation: 22008

You can use an EventBus library like this one, it's easy to use and very convenient.

Upvotes: 1

Related Questions