【发布时间】:2018-08-01 21:47:29
【问题描述】:
我创建了一个涉及与其他人聊天的应用程序,为了让聊天活动更令人赏心悦目,我创建了一个ListView 来更改每条消息的 UI。当我发送消息时,第一条消息会出现并正确显示,但是如果我发送另一条消息,它将覆盖 listView 中的前一条消息,而不是仅仅向列表视图添加另一个值,这是我的代码:
聊天活动:
private void append_chat_conversation(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Log.e("Chat details: ", String.valueOf(ds));
chat_username = dataSnapshot.child("username").getValue(String.class);
chat_msg = dataSnapshot.child("message").getValue(String.class);
Chat chat = new Chat(chat_username, chat_msg);
ArrayList<Chat> chatList = new ArrayList<>();
chatList.add(chat);
chatListAdapter adapter = new chatListAdapter(this, R.layout.chat_message, chatList);
mListView.setAdapter(adapter);
Log.e("Chat username: ", "" + chat_username);
Log.e("Chat message: ", "" + chat_msg);
}
}
聊天列表适配器:
public class chatListAdapter extends ArrayAdapter<Chat> {
private Context mContext;
int mResource;
TextView usernameTV, messageTV;
public chatListAdapter(Context context, int resource, ArrayList<Chat> objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
String username = getItem(position).getUsername();
String message = getItem(position).getMessage();
Chat chat = new Chat(username, message);
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
usernameTV = convertView.findViewById(R.id.username_chat);
messageTV = convertView.findViewById(R.id.message_chat);
usernameTV.setText(username);
messageTV.setText(message);
return convertView;
}
}
我不会添加其他代码(getter 和 setter 或单个消息的实际布局),因为我认为这不是问题。如果您需要其他任何东西,请告诉我,我确定我在这里做了一些愚蠢的事情来实现这一点,
谢谢,内森
编辑:
我终于找到了如何在不覆盖此代码的情况下添加到列表视图:
private void append_chat_conversation(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Log.e("Chat details: ", String.valueOf(ds));
chat_username = dataSnapshot.child("username").getValue(String.class);
chat_msg = dataSnapshot.child("message").getValue(String.class);
Chat chat = new Chat(chat_username, chat_msg);
chatList.add(chat);
Log.e("Chat username: ", "" + chat_username);
Log.e("Chat message: ", "" + chat_msg);
}
adapter.notifyDataSetChanged();
}
数组列表和 adpater 是顶部的公共变量,但它仍然显示消息两次。我仍然需要为此找到解决方法。感谢您的帮助
【问题讨论】:
标签: java android firebase listview firebase-realtime-database