I am using recyclerview to display messages in a chat window. However, when a new message is being edited, the recycler view focus should be on the last element. I expect there would be some way to shift the focus of a recyclerview to last element instead of first.
use recyclerView.smoothScrollToPosition(position);
position is your index of last item inserted. This will move your the RecyclerView
focus on the last element.
Use can add any of the two lines on your LinearLayoutManager object to scroll your recyclerview to the bottom ...
llm.setStackFromEnd(true);
OR
llm.setReverseLayout(true);
Use
recyclerView.smoothScrollToPosition(position)
adapter.notifyDataSetChanged();
where position is the index of last element
recyclerView.getAdapter().getItemCount()-1
use this to get last element.
This worked for me .
There are 2 ways by which you can do.
1: When you are creating any LayoutManager for the RecyclerView, Make the last parameter in its constructor as true
.
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this,LinearLayoutManager.HORIZONTAL,true);
2: Simply tell the RecyclerView to scroll to the last position.
recyclerView.smoothScrollToPosition(lastPosition);
use layoutManager.setStackFromEnd(true);
instead of this.
Sample
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
RecyclerView recyclerView = findViewById(R.id.list);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
Make Sure This position is the position of the item which you want to view.
recyclerView.smoothScrollToPosition(position);
You can simply use below code. Here recyclerView.getBottom() defines the position to be focus
recyclerView.smoothScrollToPosition(recyclerView.getBottom());
use the below code in Kotlin
binding.recyclerViewMessage.smoothScrollToPosition(if (list.size > 1) list.size - 1 else list.size);
this is working perfectly
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this,LinearLayoutManager.HORIZONTAL,false);
You can use app:stackFromEnd="true" in your recycler view XML code like:
<android.support.v7.widget.RecyclerView
android:id="@+id/message_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/message_input"
android:layout_alignParentTop="true"
app:stackFromEnd="true" />
layoutManager.setStackFromEnd(true);
instead of this. –
Birdbath © 2022 - 2024 — McMap. All rights reserved.
recyclerView.smoothScrollToPosition(position);
position is your index of last item inserted. – Jackofalltrades