Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

My problem is, for first time loading getItem called twice and this causes tab1 and tab2 both executed. Though tab1 only consist local data but because of twice calling tab2 executed and fetch data from server.

I don't want to execute tab2 and it's functionality while I'm in tab1 and so forth.

The getItem() code:

@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 out if you can.

like image 622
debug.error Avatar asked Dec 15 '22 14:12

debug.error


1 Answers

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...
    }
}
like image 169
vilpe89 Avatar answered Dec 21 '22 11:12

vilpe89