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?
The issue was that
onPageSelected(int position)
method wasn't being called even after setting adapter on my viewpager and calingviewPager.setCurrentItem(0);
in my activityonCreate(Bundle savedInstanceState)
method.i had to manually call
onPageSelected(int position)
through viewpager'spost()
method.Thus my overall
onCreate(Bundle savedInstanceState)
looked like thisAll other pages(fragments) are receiving the events because
onpageSelected()
will be called when on scroll away from the first page. it's only the first page that wasn't receiving the event.