在Android中使用RecyclerView聊天应用程序

时间:2017-08-07 06:09:54

标签: java android android-recyclerview

我在聊天应用程序中使用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);
    }

2 个答案:

答案 0 :(得分: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);

尝试一下,让我们知道它是否解决了问题。

答案 1 :(得分:1)

如果您是发件人,也许您可​​以添加此功能:

.... adapter{
    public void addItem(CustomClass customClass){
         yourListOfObject.add(customClass);
         notifyItemInserted(yourListOfObject.size()-1);
    }
}