如何仅在片段可见时调用 onCreateView?
我正在使用带有 5 个片段的 ViewPager,我的问题是当第一个片段可见时,它已经加载了第二个片段.
I'm using a ViewPager with 5 fragments and my problem is that when the first fragment is visible, it already loads the second one.
我读过一些关于 viewPager.setOffscreenPageLimit();
的内容,但它的默认值为 '1' 并且不能设置为 '0' 因为 ViewPager 需要这个用于滑动动画.
I read something about viewPager.setOffscreenPageLimit();
but default value for this is '1' and can't be set to '0' because ViewPager needs this for the swipe animation.
所以第二个片段会默认加载.
So the second fragment will always be loaded by default.
但我的问题是我在两个片段中都有一个全局 Arraylist,每个片段中加载了不同的值,当我在片段一上时,由于调用了第二个片段,这些值会被覆盖.
But my problem is that i have a global Arraylist in both fragments with different values loaded in each fragment and when i'm on fragment one, the values get overwritten because the second fragment is called.
当片段对用户可见时,如何只为每个片段调用 onCreateView?
How to only call onCreateView for each fragment when that fragment is visible for the user?
推荐答案
首先,我不会使用全局列表.如果您需要保存类似类型的列表,请创建一个 baseFragment.如果您的目标是在片段之间共享过滤,那么只需将应用的过滤器传递给每个片段,以便它知道如何在加载或传递列表时管理其列表,但不要使用只会自找麻烦的全局.
First, I would not use a global list. Make a baseFragment if you need to hold a similar type of list. If your goal is to share filtering among fragments, then simply pass the applied filters to each fragment so it knows how to manage its list as it loads or pass the list, but don't use a global that's just asking for trouble.
其次,onCreate 是故意在寻呼机上调用的,因此您可以在它显示在屏幕上之前预加载一些内容.这是为了在用户左右滑动时提高渲染性能.如果你在滑动发生时加载,它会很糟糕而且很糟糕.
Second, onCreate is called on the pager on purpose so you can preload some things before it shows on the screen. It's to improve rendering performance as the user swipes from side to side. If you load as the swipe happens, it will be jumpy and bad.
最后考虑将您的逻辑移至 onResume,除非您有充分的理由不这样做.如果这对您不起作用,则监视页面更改事件并调用您在每个 baseFragment 上创建的共享加载"方法,您可以在那里简单地调用和处理您的代码.
Lastly consider moving your logic to onResume, unless you have good reason not to. If that doesn't work for you, then monitor the page changing event and call a shared "load" method that you create on each baseFragment that you can simply call and handle your code there.
相关文章