Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cycle through items in Android RecyclerView?

How can you cycle through the items in an Android RecyclerView?

I would like to have a RecyclerView that scrolls horizontally. When the end is reached to the right, it simply continues scrolling by restarting the list of items. the same to the left.


For example:
List of items: 0,1,2,3,4,5,6,7,8,9
Starting view shows: 0,1,2,3,4,5,6,7
After scrolling 5 items to the right: 5,6,7,8,9,0,1,2
After scrolling 2 items to the left: 8,9,0,1,2,3,4,5

like image 762
studersi Avatar asked Feb 06 '23 12:02

studersi


1 Answers

Another idea would be, make getItemCount() of your adapter return Integer.MAX_VALUE and then in order to get your item, you would call itemsList.get(position % list.size).
This way, when the scrolling goes beyond your actual list size, it restarts from 0 and shows the first element of the list after the last one.

One more thing to do could be calling scrollToPosition(int x) on the LayoutManager where x % yourList.size() == 0 and x being somwhere close to Integer.MAX_VALUE / 2, this way the scroll would look like infinite (~1 billion positions in every direction from the starting point).

As pointed out in comment, if the list size is 0 getItemCount should return 0. E.g.

return list.size == 0 ? 0 : Integer.MAX_VALUE
like image 134
lelloman Avatar answered Feb 13 '23 07:02

lelloman