Search code examples
androidxamarinscrollandroid-recyclerviewxamarin.android

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!


Solution

  • 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);