Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically scroll to bottom of RecyclerView

I have a fragment that has a RecyclerView inside its layout file. The RecyclerView holds messages in a chat. So naturally, I need the RecyclerView to scroll to the bottom when the chat fragment gets opened.

I tried scrolling directly on the RecyclerView:

var mRecyclerView = view.FindViewById<RecyclerView>
mRecyclerView.ScrollToPosition(mMessages.Count-1);

Second method:

LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(Application.Context);
mRecyclerView.SetLayoutManager(mLinearLayoutManager);
mLinearLayoutManager.ScrollToPosition(mMessages.Count - 1);      

Third method:

LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(Application.Context);
mRecyclerView.SetLayoutManager(mLinearLayoutManager);
mLinearLayoutManager.ScrollToPositionWithOffset(mMessages.Count - 1, 0);

Unfortunately, nothing happens in either case. Any suggestions would be greatly appreciated!

like image 933
rasperryPi Avatar asked Jul 04 '17 18:07

rasperryPi


People also ask

How scroll RecyclerView to bottom in android programmatically?

You can use scrollToPosition() with the index of the last position. Based on the doc, " RecyclerView does not implement scrolling logic, rather forwards the call to scrollToPosition(int)". It does not implement the logic, simply call this function will does nothing.

What is setHasStableIds?

setHasStableIds is an optimization hint that you can give to the recycler. You're telling it "when I provide a ViewHolder , its id is unique and will not change." It's very easy to write an Adapter that does otherwise - for example, linking the id to item position.

What is LinearLayoutManager Android?

LayoutManager implementations that lays out items in a grid. WearableLinearLayoutManager. This wear-specific implementation of LinearLayoutManager provides basic offsetting logic for updating child layout. A RecyclerView. LayoutManager implementation which provides similar functionality to ListView .


1 Answers

Please use smoothScrollToPosition to fix your issue. I always use smoothScrollToPosition for redirecting to any position.

Make sure, mMessages size is good as you thinking.

Example,

RecyclerView rv = (RecyclerView)findViewById(R.id.recyclerView);
rv.smoothScrollToPosition(mMessages.count-1);
like image 98
Narendra Sorathiya Avatar answered Sep 22 '22 19:09

Narendra Sorathiya