ListView 自定义Adapter
public class MainActivity extends Activity { private List<Map<String, Object>> listItems; private String[] names; private String[] ages; private ListView lv; private MyAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); names = getResources().getStringArray(R.array.name); ages = getResources().getStringArray(R.array.age); lv = (ListView) findViewById(R.id.lv); listItems = getListItems(); adapter = new MyAdapter(MainActivity.this, listItems); lv.setAdapter(adapter); } private List<Map<String, Object>> getListItems() { List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>(); for (int i = 0; i < names.length; i++) { Map<String, Object> map = new HashMap<String, Object>(); map.put("name", names[i]); map.put("age", ages[i]); listItems.add(map); } return listItems; } }
public class MyAdapter extends BaseAdapter { private List<Map<String, Object>> listItems; private LayoutInflater inflater; public final class ListItemView { public TextView tv1; public TextView tv2; } public MyAdapter(Context context, List<Map<String, Object>> listItems) { this.listItems = listItems; inflater = LayoutInflater.from(context); } @Override public int getCount() { // TODO Auto-generated method stub return listItems.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ListItemView liv; if (null == convertView) { liv = new ListItemView(); convertView = inflater.inflate(R.layout.listitem, null); liv.tv1 = (TextView) convertView.findViewById(R.id.tv1); liv.tv2 = (TextView) convertView.findViewById(R.id.tv2); convertView.setTag(liv); } else { liv = (ListItemView) convertView.getTag(); } liv.tv1.setText((String) listItems.get(position).get("name")); liv.tv2.setText((String) listItems.get(position).get("age")); return convertView; } }