如何使用 FirebaseUI FirestoreRecyclerAdapter 像聊天应用程序一样反转 recyclerView 布局?

How to reverse recyclerView layout like a chat app with FirebaseUI FirestoreRecyclerAdapter?

我正在使用 FirestoreRecyclerAdapter 在 java 中制作一个聊天应用程序。添加消息时效果很好,但我希望消息显示在底部而不是顶部。我试过了

layoutManager.setReverseLayout(true);

layoutManager.setStackFromEnd(true);

现在它反转了它的位置,这是好的,但它不会自动滚动到底部位置。当我添加新消息时,我需要手动滚动才能看到它。

最好的方法是在有新消息时使用以下片段。您可以为此使用快照侦听器

y = (Here you need to try 2 things. My coding laptop is not with me so I cannot test and tell but either 0 should work or the chatlist.size()-1);
layoutManager.scrollToPosition(y);
OR
layoutManager.smoothScrollToPosition(y);// I do not recommend this for chat apps since it will take time to go down if there are a lot of texts below the user

添加以下行后 Recyclerview 自动滚动到底部

 new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    recyclerView.smoothScrollToPosition(0);

                }
            });
        }
    }, 1000);

如果父布局是水平滚动,上述解决方案将不起作用。

其他解决方案是

 recyclerView.scrollToPosition(0);

这两行代码都对我有用。您可以使用任何解决方案

这是我用的:

@Override
public void onStart() {
    super.onStart ();
    adapter.startListening();
    recyclerView.scrollToPosition (0);
}

也用

@Override
public void onDataChanged() {
    super.onDataChanged ();
    recyclerView1.smoothScrollToPosition (0);
}

在适配器中

我正在使用

recyclerView.scrollToPosition (0);

在 onCreate 中,适配器在 onStart 中启动。现在可以使用了