MainActivity如下:
package cc.ca; import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.SimpleAdapter; /** * Demo描述: * notifyDataSetChanged使用示例 * */ public class MainActivity extends Activity { private ListView mListView; private SimpleAdapter mSimpleAdapter; private HashMap<String, Object> mHashMap; private ArrayList<HashMap<String, Object>> mArrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init() { mListView = (ListView) findViewById(R.id.listView); mArrayList = new ArrayList<HashMap<String, Object>>(); addDataForListView(); mSimpleAdapter = new SimpleAdapter( MainActivity.this, mArrayList, R.layout.listviewitem, new String[] { "id" }, new int[] { R.id.textView }); mListView.setAdapter(mSimpleAdapter); mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) { //1 修改原本的数据 HashMap<String, Object> hashMap=mArrayList.get(position); hashMap.put("id", "click "+position); //2 重新放入ArrayList中 mArrayList.set(position, hashMap); //3 Adapter调用notifyDataSetChanged方法 mSimpleAdapter.notifyDataSetChanged(); } }); } private void addDataForListView() { for (int i = 0; i < 20; i++) { mHashMap = new HashMap<String, Object>(); mHashMap.put("id", "" + i); mArrayList.add(mHashMap); } } }
main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ListView android:id="@+id/listView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_centerInParent="true" /> </RelativeLayout>
listviewitem.xml如下:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/textView" android:layout_width="fill_parent" android:gravity="center" android:layout_height="80dip" /> </RelativeLayout>