如何刷新一个Android列表视图后添加/删除动态数据?


当前回答

如果你还不满意ListView刷新,你可以看看这个片段,这是从DB加载ListView,实际上你要做的就是简单地重新加载ListView,在你执行任何CRUD操作后 这不是一个最好的编码方式,但它会刷新ListView如你所愿。

它为我工作....如果你有更好的解决方案,请分享…

.......
......
do your CRUD Operations..
......
.....
DBAdapter.open();
DBAdapter.insert_into_SingleList();
// Bring that DB_results and add it to list as its contents....
                                            ls2.setAdapter(new ArrayAdapter(DynTABSample.this,
    android.R.layout.simple_list_item_1,                        DBAdapter.DB_ListView));
                                            DBAdapter.close();

其他回答

我只能通过获得新的适配器数据来获得notifyDataSetChanged,然后为列表视图重置适配器,然后像这样调用:

    expandableAdapter = baseFragmentParent.setupEXLVAdapter();
    baseFragmentParent.setAdapter(expandableAdapter);
    expandableAdapter.notifyDataSetChanged(); 

一旦修改了适配器中的数据,就可以在适配器对象上调用notifyDataSetChanged()。

关于如何/何时调用notifyDataSetChanged()的其他细节可以在这个谷歌I/O视频中查看。

当使用SimpleCursorAdapter时,可以在适配器上调用changeCursor(newCursor)。

如果你按照android指南,使用ContentProviders从数据库中获取数据,并使用CursorLoader和CursorAdapters在ListView中显示它,那么你对相关数据的所有更改将自动反映在ListView中。

你的getContext () .getContentResolver()。notifyChange (uri, null);在ContentProvider中的游标上进行调整就足以反映这些变化。不需要额外的工作。

但是当你不使用这些时,你需要告诉适配器数据集什么时候发生变化。此外,您还需要重新填充/重新加载数据集(例如列表),然后您需要在适配器上调用notifyDataSetChanged()。

如果数据集中没有变化,notifyDataSetChanged()将不起作用。 下面是在docs-方法上面的注释

/**
 * Notifies the attached observers that the underlying data has been changed
 * and any View reflecting the data set should refresh itself.
 */

对我来说,在sql数据库中更改信息后,没有什么可以刷新列表视图(具体是可扩展的列表视图),所以如果notifyDataSetChanged()没有帮助,你可以尝试先清除你的列表,并在调用notifyDataSetChanged()后再次添加它。例如

private List<List<SomeNewArray>> arrayList;
List<SomeNewArray> array1= getArrayList(...);
List<SomeNewArray> array2= getArrayList(...);
arrayList.clear();
arrayList.add(array1);
arrayList.add(array2);
notifyDataSetChanged();

希望你能理解。