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

有些话、适合烂在心里 提交于 2020-01-14 05:26:09

问题


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>


回答1:


Try using

android:descendantFocusability="blocksDescendants"

in recyclerview. This will help you avoid autoscroll




回答2:


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());



回答3:


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

RecyclerView.scrollToPosition(0)


来源:https://stackoverflow.com/questions/56040932/how-to-prevent-recyclerview-auto-scroll-to-bottom-when-insert-new-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!