I have an activity with a Viewpager. my viewpager has several fragments. i want to send Otto event to a fragment when it is selected, thus i implement ViewPager.OnPageChangeListener
@Override
public void onPageSelected(int position) {
currentPosition = position;
switch (position){
case 0:
EventBus.getInstance().post(new TypeEvent());
break;
case 1:
EventBus.getInstance().post(new InternalEvent());
break;
}
}
Inside my first fragment
@Override
public void onStart() {
super.onStart();
EventBus.getInstance().register(this);
}
@Override
public void onStop(){
super.onStop();
EventBus.getInstance().unregister(this);
}
@Subscribe
public void init(TypeEvent event){
Logger.d("type event received");
//do something.......
}
My event bus class
public class EventBus extends Bus {
private static EventBus eventBus;
public static EventBus getInstance(){
if(eventBus == null){
eventBus = new EventBus();
}
return eventBus;
}
}
The problem is my fragments are not receiving events. what could be the problem?
Maybe when the event comes, the eventbus hasn't been registed yet, especilly at the Fragment's first initialization time.
So u can let
EventBus.getInstance().register(this);be called atonAttach()and unregister atonDettach.