The default behaviour of the recyclerview in Android is adding the new item to the top of its list when this is not the best practice for a chatting UI that needs to add a new item to the bottom of the list then scroll to the last item (the newly added), so in this short tutorial we will show how we can make this possible in two simple steps.

Force the recyclerview to add the new items to the bottom

We can do this by adding a custom layout manager to the recyclerview as following:

1
2
3
4
5
linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setMeasurementCacheEnabled(true);
rv_conversation.setLayoutManager(linearLayoutManager); //rv_conversation is our chat recycler view

Make the recycler view scroll to the bottom when the new item is added

We are using the Firestore recycler adapter to organize our chat, so we can use the following code to make the recyclerview scroll to the bottom when the activity start (onCreate() or onStart()) or if we wanted to have a refresh, for example in the case that you provided your UI with Swipe refresh to load more messages:

1
2
3
4
5
6
7
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {    
    @Override    
    public void onItemRangeInserted(int positionStart, int itemCount) {
        linearLayoutManager.smoothScrollToPosition(rv_conversation, null, 0);  //It will scroll to position 0 which is the last added item at the bottom of the recyclerview, you can change it to any position you want. 
        
}});
rv_conversation.setAdapter(adapter);

With these both steps, we can control the arranging and the scrolling of our recyclerview in the case of the Firestore recycler adapter.