I'm building a chat app and present messages using RecyclerView. Since this a chat app, last messages should appear at the bottom of the list. To achieve this I use LinearManager in the following way:
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.setStackFromEnd(true);
layoutManager.setSmoothScrollbarEnabled(false);
And it works fine if there are many messages in conversation. However, if there are only one or two messages between users, RecyclerView displays them at the bottom of the screen and puts white space above them.
Is it possible to display recycler items at the top of the screen in this case?
You can add image, or video, or text or a combination of all in the same RecyclerView. Another example can be WhatsApp chatting. The message that we send can be thought to be placed in a RecyclerView.
To be able to scroll through a vertical list of items that is longer than the screen, you need to add a vertical scrollbar. Inside RecyclerView , add an android:scrollbars attribute set to vertical .
I create everything normal and added setStackFromEnd(true)
, setReverseLayout(true)
, and use this method bellow to set list to the bottom when it have many itens, the recyclerview will start from the bottom, otherwise it will aways show comments from the top even if it have less itens then the size of the screen.
//method will set the recyclerview to the end, in other words its going to the
//end of the recyclerview, starting from the bottom.
//call scrollToBottom() after add your items in the adapter
public void scrollToBottom(){
recyclerView.scrollVerticallyTo(0);
}
RecyclerView Java
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.activity_comments_recycler_view);
LinearLayoutManager manager = LinearLayoutManager(this);
manager.setStackFromEnd(true);
manager.setReverseLayout(true);
recyclerView.setLayoutManager(manager);
RecyclerView XML
<RecyclerView
android:id="@+id/activity_comments_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With