Communication between Fragments in ViewPager

前端 未结 4 1034
天命终不由人
天命终不由人 2020-12-01 06:57

I\'m trying to do this: http://android-er.blogspot.com/2012/06/communication-between-fragments-in.html Except that I\'m using a FragmentStatePagerAdapter

I have an

4条回答
  •  [愿得一人]
    2020-12-01 07:46

    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);
    }
    

提交回复
热议问题