How to manage otto registration methods in ViewPag

2019-06-09 15:20发布

I am using otto to communicate service and map fragment. In the service, location provider obtains location data sends to map fragment. It works perfectly but i can not manage otto's register and unregister methods with ViewPager . This question refers neither otto nor ViewPager problem.

As mentioned above, when the service received location data it sends to map fragment. For this, i have to register/unregister fragment and service in their specific lifecycle events. At this point i am facing a problem with nature of ViewPager . By default, ViewPager firstly loads Home and Map fragments like below

enter image description here

As a result,

  1. in map fragment, otto register method being called automatically without swiping from home to map fragment
  2. in map fragment, otto unregister method never being called when swiping from it to others

So this behavior prevents me managing otto methods. Even when home or settings fragments are selected, map fragment will be alive and receiving location data from service. I do not want this.

I searched usage of otto with ViewPager on github and here, but there is no any question or example. After a bit search of ViewPager , i found some people suggests ViewPager.setOffscreenPageLimit(0). But it does not work

So whats the proper way using ViewPager and otto together?

1条回答
The star\"
2楼-- · 2019-06-09 15:46

If you want to receive only events in your MapFragment when it is visible, then you can do something like this:

public class MapFragment extends Fragment
    @Override
    public void setMenuVisibility(final boolean visible) {
        super.setMenuVisibility(visible);

        if (visible) {
            // register here
        } else {
            //unregister here
        }
}
查看更多
登录 后发表回答