Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll RecyclerView Scroll to position always on top

I'm using linear layout manager and RecyclerView with a LinearLayout Manager to populate some list of items. When I'm displaying the recyclerview for the first time and I use:

linearLayoutManager.scrollToPosition(desiredindex);

it scrolls to the top exactly where I want.

Now here is the tricky part - When I'm scrolling to top of recyclerview (i.e. new items indices will be lower than the desiredindex) and I call:

linearLayoutManager.scrollToPosition(desiredindex);

It still works fine, but when the recyclerview has been scrolled beyond the desiredindex, the recycler view scrolls such that the desiredindex item comes to the bottom rather than on top, but I want the tile to scroll to the top not the bottom.

like image 689
erluxman Avatar asked Aug 07 '16 05:08

erluxman


People also ask

How do I scroll to the top of RecyclerView?

In the above code we have added recycler view to window manger as relative parent layout and add FloatingActionButton. FloatingActionButton supports CoordinatorLayout. So we have used parent layout is CoordinatorLayout. When you click on FloatingActionButton, it will scroll to top position.

How scroll horizontal RecyclerView programmatically in Android?

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. @SoliTawako I guess scrollTo(int x, int y) you can also scroll view, but in a more fine-tuned way.

How do I make my RecyclerView smooth?

Use the setHasFixedsize method If the height of our RecyclerView items is fixed then we should use the setHasFixedsize method in our XML of our card item. This will fix the height of our RecyclerView item and prevent it from increasing or decreasing the size of our Card Layout.


1 Answers

Use scrollToPositionWithOffset like this:

linearLayoutManager.scrollToPositionWithOffset(desiredindex, 0);

scrolltopositionwithoffset(position, offset) forces the indicated item visible with indicated offset. The offset is distance from the top of RecyclerView.

like image 189
nshmura Avatar answered Sep 18 '22 12:09

nshmura