如何判断Fragment是否展示

来源:互联网 发布:淘宝卖家购物车营销 编辑:程序博客网 时间:2024/04/30 03:02

在android 开发中使用Fragment基本上是一个搞android的都知道的,他不知道方便了开发者模块化应用,而且方便开发者管理他的生命周期。但是我们很多人都是把Fragment 放到ViewPager中进行展示,让他达到更好的效果,可以滑动,可以点击切换,但是ViewPager 总是会加载当前页的前后俩页数据,那么也就会调用到其他Fragment的生命周期,可能达不到你预期的效果,如果你能知道你的Fragment什么时候展示给用户那么你就能进行一些操作来避免下。,也可以进行程序性能的优化,让你的程序更健壮。

@Overridepublic void setUserVisibleHint(boolean isVisibleToUser) {super.setUserVisibleHint(isVisibleToUser);}

这个方法是Fragment自带的,从字面意思来看他就是用来判断是否对用户来说可见。

在做应用开发的时候,一个Activity里面可能会以viewpager(或其他容器)与多个Fragment来组合使用,而如果每个fragment都需要去加载数据,或从本地加载,或从网络加载,那么在这个activity刚创建的时候就变成需要初始化大量资源。这样的结果,我们当然不会满意。那么,能不能做到当切换到这个fragment的时候,它才去初始化呢?

答案就在Fragment里的setUserVisibleHint这个方法里。请看关于Fragment里这个方法的API文档(国内镜像地址:Fragment api):

Set a hint to the system about whether this fragment's UI is currently visible to the user. This hint defaults to true and is persistent across fragment instance state save and restore.An app may set this to false to indicate that the fragment's UI is scrolled out of visibility or is otherwise not directly visible to the user. This may be used by the system to prioritize operations such as fragment lifecycle updates or loader ordering behavior.ParametersisVisibleToUser true if this fragment's UI is currently visible to the user (default), false if it is not.

这个Fragment的UI是否是可见的。所以我们只需要继承Fragment并重写该方法,即可实现在fragment可见时才进行数据加载操作,即Fragment的懒加载。


0 0
原创粉丝点击