1

In my application, I have 4 fragment into MainActivity and I use ViewPager for a show this fragments.

In each of fragments, I have API call.

But when running application run all of the API calls in this 4 fragments!

I want when click on each fragments, then run this API call.

I write API call codes and other codes into this method in fragment :

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

How can I do it? please help me

Shubham Jain
  • 2,365
  • 2
  • 17
  • 29

1 Answers1

2

That is because the fragments are already loaded when initiating the activity due to the screen page limit default value, so the code runs for all of the fragments you have to set the screen page limit to zero, so that only one fragment will load at a time:

yourViewPager.setOffscreenPageLimit(0);

according to documentation:

public void setOffscreenPageLimit(int limit) Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. Pages beyond this limit will be recreated from the adapter when needed. This is offered as an optimization. If you know in advance the number of pages you will need to support or have lazy-loading mechanisms in place on your pages, tweaking this setting can have benefits in perceived smoothness of paging animations and interaction. If you have a small number of pages (3-4) that you can keep active all at once, less time will be spent in layout for newly created view subtrees as the user pages back and forth. You should keep this limit low, especially if your pages have complex layouts. This setting defaults to 1. Parameters: limit - How many pages will be kept offscreen in an idle state.


Update:

As I figured from this question that the minimum page Limit is 1 and it can't be less than that, so the best solution would be this answer with setUserVisibleHint function to be checked in every fragment:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        // load this fragment API
    }
}
Muhammed Refaat
  • 8,914
  • 14
  • 83
  • 118