ArrayAdapter的简单使用
1、创建一个类继承ArrayAdapter
1 private class MyAdapter extends ArrayAdapter { 2 LayoutInflater in; 3 Context context; 4 int resource; 5 List<Student> students; 6 7 public MyAdapter(Context context, int resource, List<Student> students) { 8 super(context, resource, students); 9 this.context = context; 10 this.resource = resource; 11 this.students = students; 12 } 13 14 @Override 15 public int getCount() { 16 return students.size(); 17 } 18 19 @Override 20 public View getView(int position, View convertView, ViewGroup parent) { 21 22 in = LayoutInflater.from(context); 23 if (convertView == null) { 24 Log.d("MyAdapter", "创建新的convertView" + position); 25 convertView = in.inflate(resource, null); 26 } else { 27 Log.d("MyAdapter", "复用原来的convertView" + position); 28 } 29 30 TextView name = (TextView) convertView.findViewById(R.id.name); 31 TextView sex = (TextView) convertView.findViewById(R.id.sex); 32 TextView Student_id = (TextView) convertView.findViewById(R.id.Student_id); 33 TextView Myclass = (TextView) convertView.findViewById(R.id.Myclass); 34 35 Student student = students.get(position); 36 37 name.setText(student.name); 38 sex.setText(student.sex); 39 Student_id.setText(student.Student_id + ""); 40 Myclass.setText(student.aClass.name); 41 return convertView; 42 } 43 44 }
2、在Activity中
1 List<Student> students=......... 2 ListView listView = (ListView) findViewById(R.id.listView); 3 listView.setAdapter(new MyAdapter(MainActivity.this, R.layout.list_item, students)); 4 listView.setOnItemClickListener(new OnItemClickListener() { 5 6 @Override 7 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 8 Toast.makeText(getApplicationContext(), position + "", 0).show(); 9 10 } 11 });