Trần Quốc Trung
Trần Quốc Trung

Reputation: 135

how to prevent recyclerview auto scroll to bottom when insert new items?

I am using RecyclerView to view my data, but when there are many items ,RecyclerView will auto scroll to the bottom everytime a new item is inserted. how to prevent it ?

this is the insert code:

@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

    getOneMessage(dataSnapshot.getKey(), new OneMessageCallBack() {
        @Override
        public void OnCallBack(Object_Message message) {

            Object_Conversation conversation=new Object_Conversation(dataSnapshot.getKey(),message);

            mConvers_List.add(conversation);
            mConvers_Adapter.notifyItemInserted(mConvers_List.size()-1); 
        }
    });
}

this the the XML :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">


    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_conversations"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="none"
        android:background="@color/white">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>

Upvotes: 4

Views: 6155

Answers (3)

Kasiopeous
Kasiopeous

Reputation: 196

I think in order to disable the autoscroll you need to use notifyItemRangeInserted instead of notifyItemInserted. This should not make your RV scroll to the bottom.

final int positionStart = mConvers_List.size() + 1;
mConvers_List.add(conversation);
notifyItemRangeInserted(positionStart, mConvers_List.size());

Upvotes: 0

Viswanath Kumar Sandu
Viswanath Kumar Sandu

Reputation: 2274

Try using

android:descendantFocusability="blocksDescendants"

in recyclerview. This will help you avoid autoscroll

Upvotes: 7

Chithlal K
Chithlal K

Reputation: 30

You can use scrollToPosition(int position) method to scroll back to zero position.

RecyclerView.scrollToPosition(0)

Upvotes: -2

Related Questions