Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TabLayout: How to load all the tabs or only swipe refresh occur

I have an activity and i implement the android TabLayout with recyclerview. I implemented three fragments for the three tabs of the TabLayout.

The default load behavior of the TabLayout it will load and cache the neighbor tab but not the one that already loaded.

let's say Fragment A, B and C correspond to tab 1, 2 and 3 respectively.

  • When users visit tab 1 ---> Fragment A and B loaded
  • When users visit tab 2 ---> Fragment C loaded
  • But when users visit tab 1 again --> Fragment A load again.

What I want is when the activity start, I want all the three tabs load only once, then I can load the tab through refresh mechanism such as the swipe refresh.

Are there any way I can change the load behavior of the TabLayout?

Thanks,

like image 955
sayvortana Avatar asked Dec 27 '25 16:12

sayvortana


1 Answers

The viewPager by default have .setOffscreenPageLimit(1);

This way your tab's Fragment A, B and C correspond to tab 1, 2 and 3 respectively.

When users visit tab 1, fragments A and B are loaded, C isn't loaded because only tabs adjacent to tab 1 are loaded.

When you go to tab2, no tab is reloaded because they are adjacent to tab2. Instead, if you go from tab 3 to tab 1, it will be reloaded.

So you must set viewPager.setOffscreenPageLimit(2);

This way all the tabs will be loaded only once.

But if you add more tabs you must increase this number of setOffscreenPageLimit.

like image 101
Paulo Mora Avatar answered Dec 30 '25 06:12

Paulo Mora



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!