I have a RecyclerView with watching videos in it. When the user scrolls, the video should automatically play on the recyclerView elements that are visible to the user (when the scroll state is IDLE).
So, I wrote a custom onScrollListener that passes the positions that are visible to the user as an array to the startVideosOn(int[] positions) method.
But the problem is when I want to get a view by position (the position is equal to the position of the adapter). When I try linearLayoutManager.getChildAt(index) , I get null when the third element is displayed, because the RecyclerView has only 2 children to be recycled.
So, how do I get the View in RecyclerView by adapter position?
Edit, this is OnScrollListener:
public abstract class AutoPlayRecyclerOnScrollListener extends RecyclerView.OnScrollListener { LinearLayoutManager linearLayoutManager; public AutoPlayRecyclerOnScrollListener(LinearLayoutManager linearLayoutManager) { this.linearLayoutManager = linearLayoutManager; } @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (newState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) { int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition(); int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition(); if (firstVisibleItemPosition != -1 && lastVisibleItemPosition != -1) { playOn(firstVisibleItemPosition, lastVisibleItemPosition); } } } private void playOn(int lower, int upper) { int[] completelyVisibleItems = new int[upper - lower + 1]; for (int i = lower, j = 0; i <= upper; i++, j++) { completelyVisibleItems[j] = i; } playOn(completelyVisibleItems); } public abstract void playOn(int[] items); }
source share