问题
Suppose I have a recyclerview with 10 items. Out of these 10, 0 - 4 are visible in one go. On scrolling down, 0th element goes away from the screen and 5th one enters. I want to track these events - where I get to know that elements 0 - 4 are visible and then on scrolling, 1-5 are.
Is there anyway to achieve this? I want to keep track of how long a user is spending time on a particular items of the recyclerview.
回答1:
set addOnScrollListener on RecyclerView and get first and last visible rows
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
int firstVisiblePosition = ((LinearLayoutManager)recyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
int lastVisiblePosition = ((LinearLayoutManager)recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
// Now you can easily get all rows b/w first and last item
}
}
});
回答2:
You can use a grid / linear layout methods (findFirstVisibleItemPosition(), findLastVisibleItemPosition(), findFirstCompletelyVisibleItemPosition(), findLastCompletelyVisibleItemPosition()) to track the visible and completely visible item
and if you want to track is item visible on screen for some threshold means user spent enough time to view the content then you can refer to the following blog.
a very nice blog which demonstrates the use of scroll callbacks of LayoutManager and RxJava Subscribers to track item visibility meets the threshold
https://proandroiddev.com/detecting-list-items-perceived-by-user-8f164dfb1d05
来源:https://stackoverflow.com/questions/42811117/tracking-what-all-items-of-a-list-are-currently-visible-on-the-screen