请问,如何获取到RecyclerView中每个item在屏幕上显示的时长

新手上路,请多包涵

有个需求,要能获取到RecyclerView中每个item在屏幕上显示的时长,哪位大神知道

阅读 9.4k
4 个回答
只要找到View(ViewHolder)显示隐藏的调用函数,就能计算出每个View(ViewHolder)的显示时长。

很幸运的时,RecyclerView提供了这样的接口函数,而且还是两对接口函数:

1.RecyclerView#Adapter提供了一对函数:onViewAttachedToWindow(VH)onViewDetachedFromWindow(VH)

public abstract static class Adapter<VH extends ViewHolder> {
    ... ...
    
    /**
     * Called when a view created by this adapter has been attached to a window.
     *
     * <p>This can be used as a reasonable signal that the view is about to be seen
     * by the user. If the adapter previously freed any resources in
     * {@link #onViewDetachedFromWindow(RecyclerView.ViewHolder) onViewDetachedFromWindow}
     * those resources should be restored here.</p>
     *
     * @param holder Holder of the view being attached
     */
    public void onViewAttachedToWindow(VH holder) {
    }

    /**
     * Called when a view created by this adapter has been detached from its window.
     *
     * <p>Becoming detached from the window is not necessarily a permanent condition;
     * the consumer of an Adapter's views may choose to cache views offscreen while they
     * are not visible, attaching and detaching them as appropriate.</p>
     *
     * @param holder Holder of the view being detached
     */
    public void onViewDetachedFromWindow(VH holder) {
    }

    ... ...
}

2.RecyclerView提供了OnChildAttachStateChangeListener接口:

public interface OnChildAttachStateChangeListener {

    /**
     * Called when a view is attached to the RecyclerView.
     *
     * @param view The View which is attached to the RecyclerView
     */
    void onChildViewAttachedToWindow(View view);

    /**
     * Called when a view is detached from RecyclerView.
     *
     * @param view The View which is being detached from the RecyclerView
     */
    void onChildViewDetachedFromWindow(View view);
}

上面的两对接口函数,根据情况选用其一就好了,基本实现逻辑:

  1. 设置两个变量,一个用来保存AttachedToWindow被调用时的时间戳,一个用来保存显示的总时长
  2. DetachedFromWindow被调用时,计算与AttachedToWindow的时间戳差值,并将AttachedToWindow的时间戳清零,然后总时长加上这个差值
  3. AttachedToWindow后,DetachedFromWindow未被调用前,只需获取当前系统时间戳,然后计算与AttachedToWindow的时间戳差值,再加上总时长,就是总时长

可以使用HashMap记录, 在bind时, position 为key, value为一个entity, 含start和end两个成员,设置一个标记, 记录是否已经记录过时间。

第一次显示的时候获取系统时间来作为初始时间,再次显示的时候已当前系统时间减去第一次的时间

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题