且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何仅在可见片段时调用onCreateView?

更新时间:2023-12-02 23:14:40

首先,我不会使用全局列表.如果您需要保存类似类型的列表,请创建一个baseFragment.如果您的目标是在片段之间共享筛选,则只需将应用的筛选器传递给每个片段,这样它就知道如何在加载或传递列表时管理其列表,但不要使用仅是自找麻烦的全局变量.>

第二,onCreate被有意地在寻呼机上调用,因此您可以在屏幕上显示之前预加载一些内容.这是为了提高用户从一侧向另一侧滑动时的渲染性能.如果您在滑动时加载,那将是跳动且糟糕的.

最后考虑将逻辑移至onResume,除非您有充分的理由不这样做. 如果那不适合您,请监视页面更改事件,并调用在每个baseFragment上创建的共享加载"方法,您可以在其中简单地调用和处理代码.

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.

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.

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.

How to only call onCreateView for each fragment when that fragment is visible for the user?

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.

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.

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.