Get an idea of ​​RecyclerView by AdapterPosition

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); } 
+5
source share
2 answers

if you need to get a View for a visible "position", use:

 RecyclerView#findViewHolderForAdapterPosition(int position) 

or

 RecyclerView#findViewHolderForLayoutPosition(int position) 

the returned ViewHolder will contain the View you want

+11
source

You can find the solution here.

https://stackoverflow.com/a/52557308/5872337

0
source

Source: https://habr.com/ru/post/1240332/


All Articles