每当我从Firebase加载数据时,RecyclerView都会滚动到底部

时间:2019-07-30 12:51:45

标签: java android firebase firebase-realtime-database android-recyclerview

基本上,每当我将数据加载到recyclerView时,它都会自动滚动到recyclerView的底部

我的功能如下:

mMessagesDBRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                final String key = getIntent().getStringExtra("key");
                final String currentUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
                if (dataSnapshot.child(key).child(currentUid).exists() && !dataSnapshot.child(currentUid).child(key).exists()) {

                    mMessagesDBRef.child(key).child(currentUid).limitToLast(TOTAL_ITEMS_TO_LOAD* mCurrentPage).addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            mMessagesList.clear();
                            for (DataSnapshot snap : dataSnapshot.getChildren()) {
                                ChatMessage chatMessage = snap.getValue(ChatMessage.class);
                                mMessagesList.add(chatMessage);
                                populateMessagesRecyclerView();


                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });

private void populateMessagesRecyclerView() {

    adapter = new messageAdapter(mMessagesList, this);
    mChatsRecyclerView.setAdapter(adapter);



}

还有我的一些xml文件:

<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/refreshLayout"
    android:layout_below="@id/imageView11"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_above="@id/imageView14">

    <android.support.v7.widget.RecyclerView
        android:background="#f9f9f9"
        android:id="@+id/messagesRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</android.support.v4.widget.SwipeRefreshLayout>

有什么方法可以停用自动滚动功能。谢谢

1 个答案:

答案 0 :(得分:0)

在您的for循环中,将populateMessagesRecyclerView()从其中移出

...
       for (DataSnapshot snap : dataSnapshot.getChildren()) {
                                        ChatMessage chatMessage = snap.getValue(ChatMessage.class);
                                        mMessagesList.add(chatMessage);

                                    }

          populateMessagesRecyclerView();

    }
...

如果将该方法放入for循环中,它将创建x个适配器实例,并且会多次执行该工作(不作任何处理),请确保只对列表数据实例化一次适配器。< / p>

如果您来自Firebase的数据顺序错误(假设旧数据是良性数据,请先输入而不是新数据)

要解决此问题,您可以在populateMessagesRecyclerView();内反转RecyclerView

    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setReverseLayout(true);
    mChatsRecyclerView.setLayoutManager(linearLayoutManager);