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.

2
  • 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. Commented Jan 23, 2020 at 13:29
  • 1
    I think you should set offscreenPageLimit to zero, but you'll also get the same effect. Read this question Commented Jan 23, 2020 at 13:29

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

setUserVisibleHint is deprecated
setUserVisibleHint is deprecated I used the override function setMenuVisibility and it worked .
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) {
        // ...
    }

}

// ... }

1 Comment

you can try with fragment visible method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.