Get View of RecyclerView by AdapterPosition
Asked Answered
T

1

5

I have a RecyclerView with video previews in it. When the user is scrolling, the videos should automatically be played on the recyclerView-items which are visible to the user (when scroll-state is IDLE).

So I've written a custom onScrollListener which passes the positions which are visible to the user as an array to the method startVideosOn(int[] positions).

But the problem is when I want to get the View by the position (the position equals the adapter position). When I try linearLayoutManager.getChildAt(index) I get null when the 3rd item is displayed, because the RecyclerView has only 2 childs, which will be recycled.

So how do I manage to get the View of the RecyclerView by adapter position?

Edit, this is the 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);
}
Terena answered 11/1, 2016 at 10:40 Comment(4)
post you scroll listener codeMesopotamia
tried RecyclerView#findViewHolderForAdapterPosition(int position) or RecyclerView#findViewHolderForLayoutPosition(int position) ?Mesopotamia
@Mesopotamia Can you post this as an answer, so I can accept it?Terena
you can find the solution here . enter link description hereOmari
M
12

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

RecyclerView#findViewHolderForAdapterPosition(int position)

or

RecyclerView#findViewHolderForLayoutPosition(int position)

the returned ViewHolder will hold the View you want

Mesopotamia answered 11/1, 2016 at 11:7 Comment(2)
Thank you so much. I don't know why I didn't find this.Terena
Probably because it is in RecyclerView class and not in RecyclerView#Adapter wich is the one we mostly work with…Islas

© 2022 - 2024 — McMap. All rights reserved.