Communicate between different instances of same fragment

前端 未结 5 828
梦谈多话
梦谈多话 2020-12-20 19:56

The problem as follows. Let us have 3 tabs with fragments:

  • Tab 1 (Fragment A). Needs to send data to Tab 2.
  • Tab 2 (Fragment B). Needs to receive data
5条回答
  •  遥遥无期
    2020-12-20 20:33

    I'd suggest to introduce EventBus in your app.

    To add dependency - add compile 'de.greenrobot:eventbus:2.4.0' into your list of dependencies.

    Then, you just subscribe your third tab's fragment to listen to event from the first fragment.

    Something like this: in Fragment B

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        eventBus.register(this);
    }
    
    @Override
    public void onDetach() {
        eventBus.unregister(this);
        super.onDetach();
    }
    
    @SuppressWarnings("unused") // invoked by EventBus
    public void onEventMainThread(NewDataEvent event) {
        // Handle new data
    }
    

    NewDataEvent.java

    public class NewDataEvent extends EventBase {
        public NewDataEvent() {}
    }
    

    And in Fragment A just send the event:

    protected EventBus eventBus;
    ....
    eventBus = EventBus.getDefault();
    ....
    eventBus.post(new NewDataEvent());
    

    (and to avoid handling event in 2nd tab - just pass extra parameter during instantiation of fragment, if it has to listen to the event)

提交回复
热议问题