美文网首页住家
计算RecyclerView的item可见百分比

计算RecyclerView的item可见百分比

作者: 洛草为王 | 来源:发表于2019-05-10 10:49 被阅读0次

    曝光需求:根据用户滑动实时计算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;
        }
      }
    

    参考文章链接:https://stackoverflow.com/questions/39503595/how-to-find-percentage-of-each-visible-item-in-recycleview/49168492#

    相关文章

      网友评论

        本文标题:计算RecyclerView的item可见百分比

        本文链接:https://www.haomeiwen.com/subject/atpooqtx.html