how to control/modify the activity textview from viewpager fragment

删除回忆录丶 提交于 2019-11-28 14:52:03

An easier approach would be to use an EventBus . Which allows publish-subscribe-style communication between components without requiring the components to explicitly register with one another (and thus be aware of each other). It is designed exclusively to replace traditional Java in-process event distribution using explicit registration. In order to use EventBus in Android, inside your gradle(app level) add:

compile 'org.greenrobot:eventbus:3.0.0'

Now you'll need to create an Event . An event is just an object that is posted from the sender on the bus and will be delivered to any receiver class subscribing to the same event type. That's it!. So for this purpose we'll create a sample Event class:

    public class HelloWorldEvent {
    private final String message;

    public HelloWorldEvent(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

Now the next step is to create a Sender . Which allows you to post any event from any part of your whole Android application. So in your case you can send from Fragments, viewpager,etc . This is how you do it:

EventBus.getDefault().post(new HelloWorldEvent("Hello EventBus!”);

So this sends a new event, however in order to receive this, you'll need someone to receive it. So in order to listen from any activity, say from your activity class, at first you'll need to register it:

EventBus.getDefault().register(this);

Then inside that class define a new method :

// This method will be called when a HelloWorldEvent is posted
@Subscribe
public void onEvent(HelloWorldEvent event){
  // your implementation
  Toast.makeText(getActivity(), event.getMessage(), Toast.LENGTH_SHORT).show();
}

So, what happens is whenever an Event is sent, it will be received by the receiver . So You can create one Event and add multiple listeners to it. And it will work fine, as shown in the below image:

More info on the EventBus library is available here:

A simpler tutorial on EventBus is available here:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!