问题描述
我有一个活动,我用recyclerview实现了Android TabLayout.我为TabLayout的三个选项卡实现了三个片段.
I have an activity and i implement the android TabLayout with recyclerview. I implemented three fragments for the three tabs of the TabLayout.
TabLayout的默认加载行为,它将加载并缓存邻居标签,而不是已加载的邻居标签.
The default load behavior of the TabLayout it will load and cache the neighbor tab but not the one that already loaded.
假设片段A,B和C分别对应于选项卡1、2和3.
let's say Fragment A, B and C correspond to tab 1, 2 and 3 respectively.
- 用户访问标签1时--->已加载片段A和片段B
- 当用户访问选项卡2 --->片段C已加载
- 但是当用户再次访问选项卡1时–>再次加载片段A.
我想要的是活动开始时,我希望所有三个选项卡仅加载一次,然后可以通过刷新机制(如滑动刷新)加载该选项卡.
有什么方法可以更改TabLayout的加载行为吗?
谢谢
推荐答案
默认情况下,viewPager具有.setOffscreenPageLimit(1);
The viewPager by default have .setOffscreenPageLimit(1);
这样,选项卡的片段A,B和C分别对应于选项卡1、2和3.
This way your tab's Fragment A, B and C correspond to tab 1, 2 and 3 respectively.
当用户访问选项卡1时,将加载片段A和B,而不会加载C,因为仅会加载与选项卡1相邻的选项卡.
When users visit tab 1, fragments A and B are loaded, C isn't loaded because only tabs adjacent to tab 1 are loaded.
当您转到tab2时,不会重新加载任何选项卡,因为它们与tab2相邻.相反,如果您从选项卡3转到选项卡1,它将被重新加载.
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.
因此您必须设置viewPager.setOffscreenPageLimit(2);
这样,所有选项卡将仅加载一次.
This way all the tabs will be loaded only once.
但是,如果您添加更多标签,则必须增加setOffscreenPageLimit
的数量.
But if you add more tabs you must increase this number of setOffscreenPageLimit
.
这篇关于TabLayout:如何加载所有选项卡或仅发生刷卡刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!