Android 中我们经常会用到判断 View 的可见行, 当然有人会说 View.VISIBLE 就可以了, 但是有时候这个真是满足不了, 有时候我们为了优化, 在 View 滚到得不可见的时候或者由于滚到只显示了部分内容的时候不做某些操作, View.VISIBLE 这个时候是满足不了的.
1. onWindowVisibilityChanged 检测滚到导致 View 可见或者不可见
比如在 ScrollView(RecyclerView 和 ListView 等都一样) 中滚动, 会对其中的 view 产生生命周期影响, 可以参考一下: 深入理解 android view 生命周期 http://blog.csdn.net/sun_star1chen/article/details/44626433
当 ScrollView 中的 view 滚动导致 View 不可见了, 会调用 onWindowVisibilityChanged 方法, 注意是完全不可见才会调用 onWindowVisibilityChanged, 当滚到导致 View 部分可见的时候也会调用 onWindowVisibilityChanged 方法, 注意是部分可见也会调用, 这样就可以监听滚动控件中 View 的可见性.
我们可以重写 onWindowVisibilityChanged 方法:
- @Override
- protected void onWindowVisibilityChanged(int visibility) {
- super.onWindowVisibilityChanged(visibility);
- if (visibility == View.VISIBLE){
- WLog.d("danxx" ,"可见");
- // 开始某些任务
- }
- else if(visibility == INVISIBLE || visibility == GONE){
- WLog.d("danxx" ,"不可见");
- // 停止某些任务
- }
- }
2. getGlobalVisibleRect 检测 View 是部分可见或者完全可见
onWindowVisibilityChanged 方法只能判断滚动控件中 View 的可见或者不可见, 无法判断是完全可见或者是部分可见. 使用下面的方法就可以判断 View 是不是只是部分可见:
2.1 在自定义控件里面检测当前 view 是否被遮住显示不全
- /**
- *
- * @return
- */
- protected boolean isCover() {
- boolean cover = false;
- Rect rect = new Rect();
- cover = getGlobalVisibleRect(rect);
- if (cover) {
- if (rect.width()>= getMeasuredWidth() && rect.height()>= getMeasuredHeight()) {
- return !cover;
- }
- }
- return true;
- }
2.2 检测我们自己制定的 View 作为参数去判断显示情况
- /**
- * 检测制定 View 是否被遮住显示不全
- * @return
- */
- protected boolean isCover(View view) {
- boolean cover = false;
- Rect rect = new Rect();
- cover = view.getGlobalVisibleRect(rect);
- if (cover) {
- if (rect.width()>= view.getMeasuredWidth() && rect.height()>= view.getMeasuredHeight()) {
- return !cover;
- }
- }
- return true;
- }
来源: http://www.bubuko.com/infodetail-2615041.html