I have a viewpager which has five tab and control the tab with tablayout. the problem that i have is that the title doesn\'t change when want to go from one activity to an
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: