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


当前回答

如果你按照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.
 */

其他回答

你也可以用这个:

myListView.invalidateViews();

我不能得到notifyDataSetChanged()来更新我的SimpleAdapter,所以我试着先删除所有的视图,使用removeAllViews()附加到父布局,然后添加ListView,这是有效的,允许我更新UI:

LinearLayout results = (LinearLayout)findViewById(R.id.results);
ListView lv = new ListView(this);
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
SimpleAdapter adapter = new SimpleAdapter( this, list, R.layout.directory_row, 
                new String[] { "name", "dept" }, new int[] { R.id.name, R.id.dept } );

for (...) { 
    HashMap<String, String> map = new HashMap<String, String>();
    map.put("name", name);
    map.put("dept", dept);
    list.add(map);
}

lv.setAdapter(adapter);
results.removeAllViews();     
results.addView(lv);

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

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

你可以随时调用runnable:

runOnUiThread(run);

OnCreate(),你设置你的可运行线程:

run = new Runnable() {
    public void run() {
        //reload content
        arraylist.clear();
        arraylist.addAll(db.readAll());
        adapter.notifyDataSetChanged();
        listview.invalidateViews();
        listview.refreshDrawableState();
    }
};

从列表视图中删除数据后,必须调用refreshDrawableState()。 下面是例子:

final DatabaseHelper db = new DatabaseHelper (ActivityName.this);

db.open();

db.deleteContact(arg3);

mListView.refreshDrawableState();

db.close();

DatabaseHelper类中的deleteContact方法将类似于

public boolean deleteContact(long rowId) {

   return db.delete(TABLE_NAME, BaseColumns._ID + "=" + rowId, null) > 0;

}