如何仅在可见片段时调用onCreateView? [英] How to only call onCreateView when fragment is visible?

查看:77
本文介绍了如何仅在可见片段时调用onCreateView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用具有5个片段的 ViewPager ,我的问题是,当第一个片段可见时,它已经加载了第二个片段.

我读到一些有关viewPager.setOffscreenPageLimit();的信息,但此默认值是'1',并且不能设置为'0',因为 ViewPager 需要滑动动画.

因此第二个片段将始终默认加载.

但是我的问题是我在两个片段中都有一个全局Arraylist,每个片段中加载了不同的值,当我在片段1上时,由于调用了第二个片段,所以这些值被覆盖了.

如何仅在用户看到该片段时才为每个片段调用onCreateView?

解决方案

首先,我不会使用全局列表.如果您需要保存类似类型的列表,请创建一个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.

这篇关于如何仅在可见片段时调用onCreateView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆