0

I have a view pager which contains 2 fragment.

Now when user loads the activity, both of view gets loaded, they both contain analytics tag, and apps sends view tag from both of the fragments.

I want to restrict this. I want it to not execute any code from fragment2 unless user taps on it from view pager tab.

dev90
  • 7,187
  • 15
  • 80
  • 153
  • Why would you want to do this? It would cause an issue while user is trying to swipe between fragments. The best way is to load the basic shell of your view, and any other things like network calls etc. should be done when your view becomes visible – ColonD Sep 13 '18 at 12:41

3 Answers3

1

In the case of ViewPager, it is not possible I think...the minimum offScreenPageLimit is default set to 1. So it will load one page each side by default. So better you make it a custom view and load fragment according to the user taps.

Or check this workaround maybe this can be helpful in your case. I have never tried it but you can give it a shot

AbhayBohra
  • 2,047
  • 24
  • 36
1

you can do the stuff after fragment gets visible

 @Override
 public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
    }
    else {
    }
  }
Diwakar Singh
  • 267
  • 3
  • 12
1

The best implementation of a viewpager is to recycle the viewpager items. And you can achieve it by using offScreenPageLimit. However, answering your question, i have faced similar situation myself and there is no perfect solution yet to achieve such a scenario. But there are certain hacks that you can do.

One solution is to use

@Override
 public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
    }
    else {
    }
  }

This will execute only when fragment is visible to user. But this function too has some pitfalls. In some edge cases, this doesn't execute as well which will lead to an empty fragment.

The hack that I do is to use "OnTabSelectedListener" if I am integrating viewpager with tablayout and if there is only Viewpager you can override "OnPageSelectedListener".

If you are using OnTabSelectedListener, you will get callbacks in "OnTabSelected()" method when a tab is selected. So when you get the callback, use a public function in the respective fragment to load the data(Api calls, setting adapter etc).

Hope this helps

emilpmp
  • 1,716
  • 17
  • 32