java - android 中使用 RecyclerView 的聊天应用程序

标签 java android android-recyclerview

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

相关文章:

java - 实现上界通用方法

java - 服务接口(interface)没有端点! "Error"

android - 如何以编程方式检测类似IllegalArgumentException的错误: No configs match configSpec?

android - RecyclerView 项目过渡到 fragment

android - RecyclerView java.lang.IndexOutOfBoundsException : Inconsistency detected. 无效的 View 持有者适配器位置。由于更改 getItemCount()

java - 继续尝试联系服务器,直到收到响应

java - 我的自定义 JDialog 最小化并且 JScrollPane 的滚动消失

android - 如何制作不打算发布的私有(private) Chromecast 应用程序?

android - 如何一次在所有屏幕上显示单个列表项?

android - 获取 RecyclerView 中的可见项