//ListView跟SimpleAdapter的簡單運用(08) public class MainActivity extends Activity { private ListView listview; private SimpleAdapter adapter; private String[] name = { "張三", "李四", "小明", "韓梅梅", "李明" }; private int[] images = { R.drawable.img05, R.drawable.img06, R.drawable.img07, R.drawable.img08, R.drawable.img09 }; private int[] age = { 22, 23, 21, 20, 19 }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.listview = (ListView) this.findViewById(R.id.listview); List<Map<String, Object>> data = new ArrayList<Map<String, Object>>(); for (int i = 0; i < name.length; i++) { Map<String, Object> itemMap = new HashMap<String, Object>(); itemMap.put("header", images[i]); itemMap.put("name", name[i]); itemMap.put("age", age[i]); data.add(itemMap); } adapter = new SimpleAdapter(this, data, R.layout.listview, new String[] { "header", "name", "age" }, new int[] { R.id.img, R.id.name_text, R.id.age_text }); listview.setAdapter(adapter); // 注意一:Spinner只能用setOnItemSelectedListener監聽 // 而ListView用的是setOnItemClickListener,若是用setOnItemSelectedListener,ListView點擊時會沒有響應 // 2、OnItemSelectedListener // 監聽器的回調方法中,parent.getSelectedItem()和parent.getItemAtPosition(position)都能返回 // object對象。而OnItemClickListener監聽器的回調方法中parent.getSelectedItem()只能返回null。 listview.setOnItemClickListener(new OnItemClickListener() { // view每一項的對象;parent:指listview;position:每項位置;id:行號 @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Map<String, Object> items = (Map<String, Object>) adapter .getItem(position); setTitle(items.get("name").toString()); } }); } }