0

I've implemented android.support.design.widget.TabLayout in my application. The tab contains dynamic data that comes from the API and also the dynamic content in a fragment. I'm calling the Tab wise APIs. But in my fragment all APIs calling the first fragment. So, it takes too much load to show the data. I want to call API particular tab wise. When the user will click to tab then API should be called.

I've set ArrayList size to offscreenPageLimit like below

viewpager.offscreenPageLimit = mTaskStatusListResult.size

After researched I found https://stackoverflow.com/a/39455160/9635628 and set viewpager.offscreenPageLimit = 1 But still, the second tab's data are loading. i.e When a user enters the screen it loads first & second data when clicking the second tab the loads' third data. I want to prevent that. Can you pls help. It'll be appreciated.

Abid Khan
  • 2,451
  • 4
  • 22
  • 45
Komal
  • 79
  • 1
  • 10
  • I had the same problem time ago and I couldn't find a way, the way to only load the current fragment should be `offscreenPageLimit = 0` but when I tested it I found out that offscreenPageLimit internally behaves as it was 1 even if you set it to 0. – jeprubio Jan 23 '20 at 13:29
  • 1
    I think you should set `offscreenPageLimit` to zero, but you'll also get the same effect. Read [this question](https://stackoverflow.com/questions/10073214/viewpager-setoffscreenpagelimit0-doesnt-work-as-expected) – art Jan 23 '20 at 13:29

2 Answers2

2

One thing you can do is inside Fragment's setUserVisibleHint overriden method

private boolean isViewShown = false;

    @Override 
    public void setUserVisibleHint(boolean isVisibleToUser) { 
         super.setUserVisibleHint(isVisibleToUser);      
    if (getView() != null && isVisibleToUser) { 
         isViewShown = true; 
         callAPI(); 
    } else { 
         isViewShown = false; 
    } 
}

This method is called when that fragment is visible only and here you can call the required API to load data.

Abid Khan
  • 2,451
  • 4
  • 22
  • 45
1

Viewpager has default property to initialize two page at same time so you can not change that but you can setOffscreenPageLimit as par your need

ViewPager.setOffscreenPageLimit(1)

if it not working you can try another way Call API in Fragment visible method

public class MyFragment extends Fragment

{

@Override

public void setMenuVisibility(final boolean visible)

{

super.setMenuVisibility(visible);

    if (visible) {
        // ...
    }

}

// ... }