Communication between Fragments in ViewPager

  1. You could use Intents (register broadcast receiver in fragment B and send broadcasts from fragment A.
  2. Use EventBus: https://github.com/greenrobot/EventBus. It’s my favorite approach. Very convinient to use, easy communications between any components (Activity & Services, for example).

Steps to do:

First, create some class to represent event when your text changes:

public class TextChangedEvent {
  public String newText;
  public TextChangedEvent(String newText) {
      this.newText = newText;
  }
}

Then, in fragment A:

//when text changes
EventBus bus = EventBus.getDefault();
bus.post(new TextChangedEvent(newText));

in fragment B:

EventBus bus = EventBus.getDefault();

//Register to EventBus
@Override
public void onCreate(SavedInstanceState savedState) {
 bus.register(this);
}

//catch Event from fragment A
public void onEvent(TextChangedEvent event) {
 yourTextView.setText(event.newText);
}

Leave a Comment