How to cycle through items in Android RecyclerView?

时间秒杀一切 提交于 2020-01-03 17:13:41

问题


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


回答1:


another idea would be, getItemCount() of your adapter return Integer.MAX_VALUE and then in order to get your item you should do itemsList.get(position % list.size)
this way when the scrolling goes beyond your actual list size it starts from 0 again and show 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 in 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



回答2:


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



来源:https://stackoverflow.com/questions/38563932/how-to-cycle-through-items-in-android-recyclerview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!