1 package org.hjw.simpleadaptertest; 2 3 import java.util.ArrayList; 4 import java.util.HashMap; 5 import java.util.List; 6 import java.util.Map; 7 8 import android.os.Bundle; 9 import android.app.Activity; 10 import android.app.AlertDialog; 11 import android.view.Menu; 12 import android.view.View; 13 import android.view.View.OnClickListener; 14 import android.widget.AdapterView; 15 import android.widget.AdapterView.OnItemClickListener; 16 import android.widget.ListView; 17 import android.widget.SimpleAdapter; 18 19 public class MainActivity extends Activity { 20 21 private String[] names = { "虎头", "弄玉", "李清照", "李白" }; 22 private String[] descs = { "可爱的小孩", "一个很擅长音乐的女孩", "一个很擅长文学的新女性", "浪漫主义诗人" }; 23 private int[] imageIds = new int[] { R.drawable.tiger, R.drawable.nongyu, 24 R.drawable.qingzhao, R.drawable.libai }; 25 private ListView list; 26 @Override 27 protected void onCreate(Bundle savedInstanceState) { 28 super.onCreate(savedInstanceState); 29 setContentView(R.layout.activity_main); 30 31 List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>(); 32 for (int i = 0; i < names.length; i++) { 33 Map<String, Object> item = new HashMap<String, Object>(); 34 item.put("header", imageIds[i]); 35 item.put("personname", names[i]); 36 item.put("desc", descs[i]); 37 listItems.add(item); 38 } 39 40 SimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems, 41 R.layout.frag, new String[] { "header", "personname", "desc" }, 42 new int[] { R.id.header, R.id.name, R.id.desc }); 43 list=(ListView)findViewById(R.id.mylist); 44 list.setAdapter(simpleAdapter); 45 list.setOnItemClickListener(new OnItemClickListener() { 46 47 @Override 48 public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 49 long arg3) { 50 new AlertDialog.Builder(MainActivity.this).setMessage("您选中的是:"+names[arg2]).show(); 51 } 52 }); 53 } 54 55 @Override 56 public boolean onCreateOptionsMenu(Menu menu) { 57 // Inflate the menu; this adds items to the action bar if it is present. 58 getMenuInflater().inflate(R.menu.main, menu); 59 return true; 60 } 61 62 }
ps:1.simpleadapter的初始化。
第一个为上下文,第二个为列表项,第三个为界面布局文件的资源ID,第四个为列表项的Key,第五个为填充的组件.
2. 列表项资源文件的布局。