PatrickMA
PatrickMA

Reputation: 887

Get View of RecyclerView by AdapterPosition

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);
}

Upvotes: 5

Views: 6559

Answers (1)

pskink
pskink

Reputation: 24740

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

Upvotes: 12

Related Questions