Reputation: 1495
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
Upvotes: 4
Views: 4812
Reputation: 14183
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
Upvotes: 12
Reputation: 60973
I have an idea like this
First make new list = 3x original list
original list: 0,1,2,3,4,5,6,7,8,9
new list : 0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9
When first time display the RecyclerView
, your should scroll the RecyclerView
to the right 10 items (10 is the size of original list). Then if user scroll to left or right less than 10 items it will work like a circle.
And when they reach the end of the right or left, you should scroll RecyclerView
back to the state that you first time display the RecyclerView
.
Correct me if I'm wrong. Thanks for helping
Upvotes: -3