2017-08-07 49 views
0

我在我的聊天应用程序中使用了RecyclerView。我从API获取聊天列表。在Android中使用RecyclerView聊天应用程序

如果我发送任何消息,它不会在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); 
    } 
+1

究竟为什么你要为一个新的适配器和新的布局管理器每次你得到的响应时间? – EpicPandaForce

回答

0

你可以有一个了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); 

尝试,让我们知道,如果它解决了这个问题。

+0

嗨,我在哪里调用updateData(yourItems)方法。 –

+0

在onResponse方法中:updateData(resp.getData); –

1

,如果它是你的发送者,也许你可以添加此功能:

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