How do I create a circular (endless) RecyclerView?
The other solutions i found for this problem work well enough, but i think there might be some memory issues returning Integer.MAX_VALUE in getCount() method of recycler view.
To fix this, override getItemCount() method as below :
@Override
public int getItemCount() {
return itemList == null ? 0 : itemList.size() * 2;
}
Now wherever you are using the position to get the item from the list, use below
position % itemList.size()
Now add scrollListener to your recycler view
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int firstItemVisible = linearLayoutManager.findFirstVisibleItemPosition();
if (firstItemVisible != 0 && firstItemVisible % itemList.size() == 0) {
recyclerView.getLayoutManager().scrollToPosition(0);
}
}
});
Finally to start auto scrolling, call the method below
public void autoScroll() {
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
recyclerView.scrollBy(2, 0);
handler.postDelayed(this, 0);
}
};
handler.postDelayed(runnable, 0);
}
There is no way of making it infinite, but there is a way to make it look like infinite.
in your adapter override
getCount()
to return something big likeInteger.MAX_VALUE
:@Override public int getCount() { return Integer.MAX_VALUE; }
in
getItem()
andgetView()
modulo divide (%) position by real item number:@Override public Fragment getItem(int position) { int positionInList = position % fragmentList.size(); return fragmentList.get(positionInList); }
at the end, set current item to something in the middle (or else, it would be endless only in downward direction).
// scroll to middle item recyclerView.getLayoutManager().scrollToPosition(Integer.MAX_VALUE / 2);