Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll horizontal RecyclerView programmatically?

I have a horizontal RecyclerView and two button (Next,Previous) as shown in the image below.

enter image description here

so i need to move to the next item or position by use these buttons , i know about method called scrollTo but i don't know how does it work

like image 747
Ahmad Alkhatib Avatar asked Aug 16 '15 13:08

Ahmad Alkhatib


People also ask

How do I scroll end of RecyclerView programmatically?

You can use scrollToPosition() with the index of the last position.

What is linear LayoutManager?

LinearLayoutManager shows items in a vertical or horizontal scrolling list. GridLayoutManager shows items in a grid. StaggeredGridLayoutManager shows items in a staggered grid.

What is RecyclerView in android with example?

RecyclerView is the ViewGroup that contains the views corresponding to your data. It's a view itself, so you add RecyclerView into your layout the way you would add any other UI element. Each individual element in the list is defined by a view holder object.


2 Answers

I found the answer:

case R.id.next:
    mRecyclerView.getLayoutManager().scrollToPosition(linearLayoutManager.findLastVisibleItemPosition() + 1);
    break;
case R.id.pre:
    mRecyclerView.getLayoutManager().scrollToPosition(linearLayoutManager.findFirstVisibleItemPosition() - 1);
    break;
like image 74
Ahmad Alkhatib Avatar answered Oct 02 '22 12:10

Ahmad Alkhatib


RecyclerViews have a methods which they expose for scrolling to a certain position:

Snap scroll to a given position:

mRecyclerView.scrollToPosition(int position)

Smooth scroll to a given position:

mRecyclerView.smoothScrollToPosition(int position)

For these methods to work, the LayoutManager of the RecyclerView needs to have implemented these methods, and LinearLayoutManager does implement these in a basic manner, so you should be good to go.

like image 41
Gil Moshayof Avatar answered Oct 02 '22 14:10

Gil Moshayof