Reputation: 1533
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.
Upvotes: 26
Views: 49291
Reputation: 379
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this,LinearLayoutManager.HORIZONTAL,false);
Upvotes: 0
Reputation: 283
use the below code in Kotlin
binding.recyclerViewMessage.smoothScrollToPosition(if (list.size > 1) list.size - 1 else list.size);
this is working perfectly
Upvotes: 0
Reputation: 1114
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);
Upvotes: 2
Reputation: 521
You can simply use below code. Here recyclerView.getBottom() defines the position to be focus
recyclerView.smoothScrollToPosition(recyclerView.getBottom());
Upvotes: 1
Reputation: 1253
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);
Upvotes: 2
Reputation: 45
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" />
Upvotes: -1
Reputation: 782
Make Sure This position is the position of the item which you want to view.
recyclerView.smoothScrollToPosition(position);
Upvotes: 1
Reputation: 836
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 .
Upvotes: 13
Reputation: 9223
use recyclerView.smoothScrollToPosition(position);
position is your index of last item inserted. This will move your the RecyclerView
focus on the last element.
Upvotes: 52
Reputation: 439
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);
Upvotes: 18