问题描述
我正在使用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开始。现在可以了