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) {
}
... ...
}
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);
}
很幸运的时,
RecyclerView
提供了这样的接口函数,而且还是两对接口函数:1.
RecyclerView#Adapter
提供了一对函数:onViewAttachedToWindow(VH)
和onViewDetachedFromWindow(VH)
2.
RecyclerView
提供了OnChildAttachStateChangeListener
接口:上面的两对接口函数,根据情况选用其一就好了,基本实现逻辑:
AttachedToWindow
被调用时的时间戳,一个用来保存显示的总时长DetachedFromWindow
被调用时,计算与AttachedToWindow
的时间戳差值,并将AttachedToWindow
的时间戳清零,然后总时长加上这个差值AttachedToWindow
后,DetachedFromWindow
未被调用前,只需获取当前系统时间戳,然后计算与AttachedToWindow
的时间戳差值,再加上总时长,就是总时长