MH. Abdi
MH. Abdi

Reputation: 308

RecyclerView infinite scroll in both directions

I want to implement a RecyclerView that never finishes. Before the first item there is the last item and after the last item is scrolled, the first item is shown. How can I do that? What Im trying to achieve is a music player that shows the current song, the song before and after. Like this: enter image description here

(ps. is there a better way than using a recyclerview?)

Upvotes: 3

Views: 3977

Answers (2)

shivam chawla
shivam chawla

Reputation: 57

I've implemented it in a simpler way with explanation, you or anyone for reference can check this https://stackoverflow.com/a/76364112/10058095

Upvotes: 0

Cheticamp
Cheticamp

Reputation: 62831

The way I have seen this done is to define the number of items that you have to display as Integer.MAX_VALUE. In onBindViewHolder() of the adapter you will have something like:

@Override
public int getItemCount() {
    return (mItems == null) ? 0 : Integer.MAX_VALUE;
}

Now you can't really have Integer.MAX_VALUE items to display, so this is a small lie to the RecyclerView. In your code, map the index value from 0...Integer.MAX_VALUE-1 to 0...your_item_count-1 like this in onBindViewHolder():

int realPos = position % mItems.size();

Use realPos instead of the position that the RecyclerView passes in.

All that is left is to scroll the RecyclerView to the middle of the range:

mRecycler.scrollToPosition(Integer.MAX_VALUE / 2);

This works OK, but is it perfect? No, but close enough; I don't think anyone will scroll enough to see the flaw. (It will stop wrapping at the extremes.)

Upvotes: 6

Related Questions