当适配器数据更改时更新列表视图

当与数组适配器相关联的数据发生更改时,使列表视图无效就足以显示更新的值吗?下面的代码不起作用,我是不是误解了什么。?

public class ZeroItemListActivity extends Activity {
private ArrayList<String> listItems=new ArrayList<String>();
private ListView mMyListView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mMyListView=(ListView) findViewById(R.id.MyListView);
mMyListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,listItems));
}
public void addItem(View v){
listItems.add("list Item");
mMyListView.invalidate();
}
}

使用的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello" />
<ListView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/MyListView"></ListView>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/AddItemsButton"
android:text="Add Items" android:onClick="addItem"></Button>
</LinearLayout>
230621 次浏览

substitute:

mMyListView.invalidate();

for:

((BaseAdapter) mMyListView.getAdapter()).notifyDataSetChanged();

If that doesnt work, refer to this thread: Android List view refresh

Change this line:

mMyListView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
listItems));

to:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
listItems)
mMyListView.setAdapter(adapter);

and after updating the value of a list item, call:

adapter.notifyDataSetChanged();

invalidate(); calls the list view to invalidate itself (ie. background color)
invalidateViews(); calls all of its children to be invalidated. allowing you to update the children views

I assume its some type of efficiency thing preventing all of the items to constantly have to be redraw if not necessary.

I found a solution that is more efficient than currently accepted answer, because current answer forces all list elements to be refreshed. My solution will refresh only one element (that was touched) by calling adapters getView and recycling current view which adds even more efficiency.

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Edit object data that is represented in Viewat at list's "position"
view = mAdapter.getView(position, view, parent);
}
});