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


当前回答

如果你想从一个服务中更新UI listview,那么在你的Main活动中使适配器静态,并这样做:

@Override
public void onDestroy() {
    if (MainActivity.isInFront == true) {
        if (MainActivity.adapter != null) {
            MainActivity.adapter.notifyDataSetChanged();
        }

        MainActivity.listView.setAdapter(MainActivity.adapter);
    }
}    

其他回答

我不能得到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);

如果你想从一个服务中更新UI listview,那么在你的Main活动中使适配器静态,并这样做:

@Override
public void onDestroy() {
    if (MainActivity.isInFront == true) {
        if (MainActivity.adapter != null) {
            MainActivity.adapter.notifyDataSetChanged();
        }

        MainActivity.listView.setAdapter(MainActivity.adapter);
    }
}    

我认为这取决于你对刷新的定义。您的意思是应该刷新GUI显示,还是应该刷新子视图,以便您可以通过编程调用getChildAt(int)并获得与适配器中内容对应的视图?

如果希望刷新GUI显示,则调用适配器上的notifyDataSetChanged()。下次重绘时,GUI将被刷新。

如果您希望能够调用getChildAt(int)并获得反映适配器中的内容的视图,则调用layoutChildren()。这将导致从适配器数据重构子视图。

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

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

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