我有一个listview,我在固定时间间隔后向其中添加一些数据。但是我不想再次设置适配器,因为它会刷新整个列表。是否有一种方法可以在不刷新整个列表的情况下添加项目。
提前感谢。
提前感谢。
RecycleView
而不是ListView
中使用以下内容:notifyItemInserted(0);//NOT notifyDataChanged()
recyclerViewSource.scrollToPosition(0);
//Scroll up, to use this you'll need an instance of the adapter's RecycleView
您可以调用 adapter.notifyDataSetChanged()
来更新列表。
Adapter 的 getView()
在不同的时间被调用,没有特定的模式。因此,当 ListView
希望更新视图时,您的视图会被更新。
但就我所看到的,您正在寻找 adapter.notifyDataSetChanged
。工作流程应该是这样的。
Set adapter to ListView
Add data to adapter`
Call notifyDataSetChanged() on adapter.
这将至少防止您的列表反弹回到列表的第一项。希望有所帮助。
您可以使用
adapter.add(<new data item>); // to add data to your adapter
adapter.notifyDatasetChanged(); // to refresh
例如。
ArrayAdapter<String> adapter;
public void onCreate() {
....
....
ArryList<String> data = new ArrayList<String>();
for(int i=0; i<10; i++) {
data.add("Item " + (i+1));
}
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
setListAdapter(adapter);
}
现在,每当您有新数据要添加到列表中时,可以执行以下操作
private void appendToList(ArrayList<String> newData) {
for(String data : newData)
adapter.add(data);
adapter.notifyDatasetChanged();
}
你可以使用这个 .notifyDataSetChanged()
然而 notifyDataSetChanged() 只适用于 ArrayAdapter,如果你在 Adapter 上使用 add、insert、remove 和 clear 函数。