判断当前fragment是否可见

来源:互联网 发布:钢铁力量数据 编辑:程序博客网 时间:2024/05/17 06:33

参考http://blog.csdn.net/jiangwei0910410003/article/details/17199219


由于在ViewPage中PageAdapter来管理所有的Fragment。在加载一个Fragment的时候,会自动缓存左右几个(默认是一个)页面,此时也会调用到正常的生命周期函数,onCreate,onCrateView,onResume.可是这样就干扰了我们统计页面打开次数。

例如:一个ViewPager中存在三个页面的时候,当默认是第一个页面,并且被打开。那么在我们的后台就会收集到用户打开两个页面的信息。这个对我们的统计就是一个很大的干扰。所以就不能再将统计代码放在onResume中,要放在一个其他的函数内,但问题的关键是如何确认当前的Fragment可见?这样我才能把统计函数移植过去。同时Fragment虽然有onResume和onPause的,但是这两个方法是Activity的方法,调用时机也是与Activity相同,和ViewPager搭配使用这个方法就很鸡肋了,根本不是你想要的效果,这里介绍一种方法。


在问这个问题的时候把焦点都放在生命周期的触发上了。发现Fragment下专门有一个setUserVisibleHint函数来处理这个事情:

@Override  public void setUserVisibleHint(boolean isVisibleToUser) {      super.setUserVisibleHint(isVisibleToUser);      if (isVisibleToUser) {          //相当于Fragment的onResume      } else {          //相当于Fragment的onPause      }  }  



API是这么说的:

Set a hint to the system about whether thisfragment'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.
Parameters
isVisibleToUsertrueif this fragment's UI is currently visible to the user (default),falseif it is not.

简单来说,就是isVisibleToUser这个值如果是真,用户就能看见这个fragment,如果为假,说明这个fragment对当前用户不可见。

我使用他的目的如下:

在fragment中,有一些操作会使当前fragment界面改变,比如设置一些控件android:visiable="gone"

此时切换到其他fragment再切换回来的时候,该fragment的界面是改变后的界面,这是不符合用户预期的。

这个fragment应该处于初始界面,也就是对控件的visiable在上面的方法中进行设置。


这个方法的另外一个功能是实现懒加载。就是本来android会提前自动加载一些fragment,当我们需要完全手动加载的时候,可以把一些初始化的设置写在这个方法里。


就是酱!


0 0
原创粉丝点击