我在聊天应用程序中使用 RecyclerView。我从 API 获取聊天列表。
如果我发送任何消息,它不会在 RecyclerView 中更新。如果我返回并查看该 Activity ,它会在 RecyclerView 中更新。我使用的 adapter.notifyDataSetChanged();
不起作用。
call.enqueue(new Callback<LiveChatGetMsgResponse>() {
@Override
public void onResponse(Call<LiveChatGetMsgResponse> call, Response<LiveChatGetMsgResponse> response) {
if (response.isSuccessful()) {
LiveChatGetMsgResponse resp = response.body();
//Here i get the message list, i send this list to adapter class
msg_list = resp.getData();
myLinear=new LinearLayoutManager(ChatActivity.this);
myLinear.setReverseLayout(true);
recyclerChatList.setLayoutManager(myLinear);
adapter = new LiveChatListAdapter(getApplicationContext(), msg_list);
recyclerChatList.setAdapter(adapter);
//i use this method to scrroll down the RecyclerView
scrollToBottom();
}
}
@Override
public void onFailure(Call<LiveChatGetMsgResponse> call, Throwable t) {
Log.e("LiveChatGetMsgFailure",t.getMessage());
}
});
private void scrollToBottom() {
adapter.notifyDataSetChanged();
if (adapter.getItemCount() < 1)
recyclerChatList.getLayoutManager().smoothScrollToPosition(recyclerChatList, null, adapter.getItemCount() - 1);
}
最佳答案
您可以在适配器中使用 updateData 方法,如下所示
public void updateData(List<YourItem> yourItems){
mData.clear();
mData.addAll(yourItems);
notifyDatasetChanged();
}
避免在每次迭代中仅仅因为数据发生变化而创建新的适配器。
还要避免在每次迭代中设置所有内容
// Delete these lines
myLinear=new LinearLayoutManager(ChatActivity.this);
myLinear.setReverseLayout(true);
recyclerChatList.setLayoutManager(myLinear);
adapter = new LiveChatListAdapter(getApplicationContext(), msg_list);
尝试一下,让我们知道它是否解决了问题。
关于java - android 中使用 RecyclerView 的聊天应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45540381/