getItem called twice and this causes tab1 and tab2 both executed in FragmentPagerAdapter

南笙酒味 提交于 2019-12-04 09:48:58

In ViewPager there is a limit how many screens (Fragments) your ViewPager will load. You can set this by calling ViewPagers setOffscreenPageLimit method.

HOWEVER if you inspect the ViewPagers code, it tells you that you must atleast load 1 offscreen page:

private static final int DEFAULT_OFFSCREEN_PAGES = 1;

public void setOffscreenPageLimit(int limit) {
    if (limit < DEFAULT_OFFSCREEN_PAGES) {
        Log.w(TAG, "Requested offscreen page limit " + limit 
            + " too small; defaulting to " + DEFAULT_OFFSCREEN_PAGES);
        limit = DEFAULT_OFFSCREEN_PAGES;
    }
    // ...
}

Bottom line: I don't think you can load the current Fragment only, sorry.

EDIT: But you can do something like this in your Fragments if you want to load, lets say, data from network only when Fragments comes visible to user:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        // Fetch data or something...
    }
}

When you have two fragments in a tab, normally both fragments will start and will be running "in parallel". This is a normal behaviour. You can use some sort of EventBus or similar to manually control the lifecycle of the fragments.

Yes. call this method in each fragment and call your methods and etc on it:

  override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if(isVisibleToUser)
            loadData() 
    }
  • Don't write it in the first fragment!
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!