在为我的ListView初始化自定义适配器后,它绘制了数据集的第一部分。现在,我想在列表视图的底部添加其他视图。但是当我使用notifyDataSetChanged时,它不会刷新列表视图。
设置
ListView messages = findViewById(R.id.latest_messages);
adapter = new AdapterChat(getApplicationContext(),
R.layout.element_chat_other, inputItems);
messages = (ListView) findViewById(R.id.messages);
messages.setAdapter(adapter);
messages.setSmoothScrollbarEnabled(true);
更新不起作用:
i在arraylist中添加一个新对象,然后重新调用适配器以刷新数据。但是视图仍然没有显示:
inputItems.add(new DTOChat(fromCC,messageCC, tsCC, idCC));
adapter = new AdapterChat(getApplicationContext(),
R.layout.element_chat_other, inputItems);
adapter.notifyDataSetChanged();
尝试这样
inputItems.add(new DTOChat(fromCC,messageCC, tsCC, idCC));
// here no need to create new adapter instance only add below line
adapter.notifyDataSetChanged();
使用以下语句,将AdapterChat
的实例分配给适配器
adapter = new AdapterChat(getApplicationContext(),
R.layout.element_chat_other, inputItems);
然后您将此实例设置为ListView
的适配器
messages.setAdapter(adapter);
一段时间后,您将新项目添加到数据列表inputItems并将AdapterChat
的另一个实例分配给adapter
inputItems.add(new DTOChat(fromCC,messageCC,tsCC,idCC));adapter = new AdapterChat(getApplicationContext(),R.layout.element_chat_other,inputItems);
现在,旧实例仍设置为当前ListView
适配器,但是当您调用adapter.notifyDataSetChanged();
时,您会通知最近创建的实例,该实例已分配给adapter。
您可以保持adapter的状态(不创建新实例),只需将新项目添加到inputItems中,然后直接调用
adapter.notifyDataSetChanged();