曝光需求:根据用户滑动实时计算item可见的百分比,超过50%则计为有效曝光。
代码如下:
private void calculateItemVisiblePercent() {
if (mRecyclerView == null || mLayoutManager == null || mAdapter == null) return;
//获取第一个可见item的位置
final int firstPosition = mLayoutManager.findFirstVisibleItemPosition();
//获取最后一个可见item的位置
final int lastPosition = mLayoutManager.findLastVisibleItemPosition();
Rect rvRect = new Rect();
//获取recyclerview可见区域相对屏幕左上角的位置坐标
mRecyclerView.getGlobalVisibleRect(rvRect);
for (int position = firstPosition; position <= lastPosition; position++) {
int visiblePercent;
//根据position获得对应的view
View itemView = mLayoutManager.findViewByPosition(position);
int itemHeight = itemView.getHeight();
Rect rowRect = new Rect();
//获取item可见区域相对屏幕左上角的位置坐标
itemView.getGlobalVisibleRect(rowRect);
if (rowRect.bottom >= rvRect.bottom) { //item在recyclerview底部且有部分不可见
int visibleHeightFirst = rvRect.bottom - rowRect.top;
visiblePercent = (visibleHeightFirst * 100) / itemHeight;
} else { //item在recyclerview中或顶部
int visibleHeightFirst = rowRect.bottom - rvRect.top;
visiblePercent = (visibleHeightFirst * 100) / itemHeight;
}
if (visiblePercent > 100) visiblePercent = 100;
}
}