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


当前回答

如果你想在刷新时保持你的滚动位置,你可以这样做:

if (mEventListView.getAdapter() == null) {
    EventLogAdapter eventLogAdapter = new EventLogAdapter(mContext, events);
    mEventListView.setAdapter(eventLogAdapter);
} else {
    ((EventLogAdapter)mEventListView.getAdapter()).refill(events);
}

public void refill(List<EventLog> events) {
    mEvents.clear();
    mEvents.addAll(events);
    notifyDataSetChanged();
}

有关详细信息,请参阅Android ListView:刷新时保持您的滚动位置。

其他回答

你也可以用这个:

myListView.invalidateViews();

如果你还不满意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();

如果您正在使用SimpleCursorAdapter,请尝试在Cursor对象上调用requery()。

你可以随时调用runnable:

runOnUiThread(run);

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

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

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