[英]Chat Application with RecyclerView in android
我在聊天应用程序中使用RecyclerView。 我从API获取聊天列表。
如果我发送任何消息,则RecyclerView中不会更新。 如果我回去参加那个活动,它会在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);
试试看,让我们知道它是否解决了问题。
如果是您是发送者,也许您可以添加以下功能:
.... adapter{
public void addItem(CustomClass customClass){
yourListOfObject.add(customClass);
notifyItemInserted(yourListOfObject.size()-1);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.