How to manage otto registration methods in ViewPager

余生颓废 提交于 2019-12-08 13:48:33

问题


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

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:


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
        }
}


来源:https://stackoverflow.com/questions/32059742/how-to-manage-otto-registration-methods-in-viewpager

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