一,view.getLocalVisibleRect(rect);以目标view的左上角为参考系;
view.getGlobalVisibleRect(rect);以屏幕的左上角为参考系;
二,在recycler的一个item中,写了一个textview,滑动recyclerview使textview从可见到不可见,测试代码如下:
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
View viewByPosition = layoutManager.findViewByPosition(0);
RecyclerView.ViewHolder childViewHolder = recyclerView.getChildViewHolder(viewByPosition);
if (childViewHolder instanceof MyViweHolder) {
Rect r = new Rect();
boolean localVisibleRect1 = ((MyViweHolder) childViewHolder).tvNumber.getLocalVisibleRect(r);
// 如果tvNumber处于完全可见的位置,r.top一直为0,当顶部部分滑动到不可见,r.top开始从1开始递增,
// 递增到tvNumber的height的高度时,tvNumber就完全不可见了,此时r.top的值突变为-height的值,
Log.i(TAG, "onScrolled: "+localVisibleRect1+r.top);
}
}
});
输出的log太多,关键点截图
1,tvNumber一直为可见时,r.top一直为0;从部分不可见开始,r.top的值为1到view.height,递增
2.完全不可见时,r.top的值从-height开始,负的数递减
3.判断view是否完全可见:rect.top==0
public static boolean isVisibleLocal(View target){
Rect rect =new Rect();
target.getLocalVisibleRect(rect);
return rect.top==0;
}