3

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?)

MH. Abdi
  • 298
  • 5
  • 22
  • Do you have try somethings. And can we see it (code) to more understand what you want. – Crammeur Jul 23 '18 at 15:24
  • 1
    @crammeur thank you for answering but I just realized how I can fix that! All I needed was to implement a doubly linked list and use it in recyclerview adapter! I forgot that I don't always have to use ArrayList class in adapter! I'm writing the custom list class, I'll post it when It's done :) – MH. Abdi Jul 23 '18 at 15:28

2 Answers2

6

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.)

Cheticamp
  • 61,413
  • 10
  • 78
  • 131
  • Yes I think It works! However its better to use `mRecycler.scrollToPosition((Integer.MAX_VALUE / 2)-(Integer.MAX_VALUE / 2)% mItems.size());` instead, to scroll to the first item. ps. does this way make performance issues? because of all the big numbers – MH. Abdi Jul 23 '18 at 15:53
  • 2
    @Apptic I just positioned randomly. As for performance issues, you aren't really keeping that large of an array and `RecyclerView` just maintains a small pool of view holders so, no, I don't think that there is a performance hit. – Cheticamp Jul 23 '18 at 16:00
0

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