Automatically scroll to bottom of RecyclerView
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);
I believe you are not calling it in right way. You have to pass LinearLayoutManager as well along with recycler view to make it work. Here how I have made it work
mLayoutManager.smoothScrollToPosition(mRecyclerView, null, array.size() - 1);
It's Simple change your code with
RecyclerView recyclerView = findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(mAdapter);
recyclerView.smoothScrollToPosition(mAdapter.getItemCount());
If You have given ScrollView or NestedScrollView in the parent of RecyclerView then it will not work. Because it only works when RecyclerView doesn't have any parent layout like ScrollView. hope it will fix your error.
You can set setStackFromEnd=true
that will set the view to show the last element, the layout direction will remain the same.
After edit I have updated: just like this:
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(Application.Context);
mLinearLayoutManager.setStackFromEnd(true);
mRecyclerView.SetLayoutManager(mLinearLayoutManager);
mRecyclerView.scrollToPosition(mMessages.Count-1);
please check the documentation.
Edit: the problem is you are calling scrollToPosition without setting any layout manager to the recyclerview.
Considering to the scrollToPosition function in RecyclerView class, your case makes sense.
/**
* Convenience method to scroll to a certain position.
*
* RecyclerView does not implement scrolling logic, rather forwards the call to
* {@link android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition(int)}
* @param position Scroll to this adapter position
* @see android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition(int)
*/
public void scrollToPosition(int position) {
if (mLayoutFrozen) {
return;
}
stopScroll();
if (mLayout == null) {
Log.e(TAG, "Cannot scroll to position a LayoutManager set. " +
"Call setLayoutManager with a non-null argument.");
return;
}
mLayout.scrollToPosition(position);
awakenScrollBars();
}
Cannot scroll to position a LayoutManager set. Call setLayoutManager with a non-null argument.