GetItem is called twice, and this causes tab1 and tab2 to execute in the FragmentPagerAdapter

I have a swipe tab with three different fragments for three tabs. The getItem method in the FragmentPagerAdapter is called twice. My first tab loads local data and has a different layout than the next two tabs (tab2, tab3). Tab2 and Tab3 retrieve data from the server and load accordingly.

My problem is that the first time getItem gets loaded twice, and this causes tab1 and tab2 to execute. Although tab1 consists only of local data, due to a double call to tab2, data is also fetched from the server.

I do not want to execute tab2 and its functionality while I am in tab1, etc.

Code getItem():

@Override public Fragment getItem(int position) { 
    Fragment fragment = null; 
    switch (position) { 
        case 0: fragment = new CommentFragment(); break; 
        case 1: fragment = new AllPostFragment(); break; 
        case 2: fragment = new TodayFragment(); break; 
    } 
    return fragment; 
}

So I'm looking for a solution. Please help me if you can.

+4
3

ViewPager (), ViewPager. , ViewPagers setOffscreenPageLimit.

, ViewPagers, , , , 1 :

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;
    }
    // ...
}

: , , .

EDIT: - , , , , :

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

, "". . EventBus .

0

Yes. call this method in each fragment and call your methods, etc. On him:

  override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if(isVisibleToUser)
            loadData() 
    }
  • Do not write it in the first fragment!
0
source

Source: https://habr.com/ru/post/1588937/


All Articles