问题
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,
回答1:
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
.
来源:https://stackoverflow.com/questions/34622358/tablayout-how-to-load-all-the-tabs-or-only-swipe-refresh-occur