gtvario
gtvario

Reputation: 11

Sending Data to a Fragment from a Fragment in a Tabbed Activity

I have a tabbed activity with four tabs. Each tab has its own unique fragment. I want to collect data from the first three tabs, analyze it, and send the analyzed data to a TextView in the fourth tab. How would I do this?

Upvotes: 0

Views: 33

Answers (1)

Anuj
Anuj

Reputation: 1940

There's two solutions I can think of,

First, keep a reference of all the 4 tabs in your activity. From your fragments, you can access the activity with getActivity() and call the relevant update function.

public class YourActivity {
   ...
   public void updateFourthFragment(Object data) {
       fourthFragment.update();
   }
}

public class FirstFragment {
   ...
   public void onInput() {
       ((YourActivity) getActivity()).updateFourthFragment(input);
   }
}
...

Second, use an event bus, like http://square.github.io/otto/

public class FirstFragment {
    ...
    public void onInput() {
        bus.post(new InputEvent(input));
    }
}

public class FourthFragment {
    ...
    @Subscribe
    public void onInputEvent(InputEvent event) {
        handleInput(event.getInput());
    }
}

Upvotes: 1

Related Questions