1、创建一个类继承ArrayAdapter
private class MyAdapter extends ArrayAdapter {
LayoutInflater in;
Context context;
int resource;
List<Student> students; public MyAdapter(Context context, int resource, List<Student> students) {
super(context, resource, students);
this.context = context;
this.resource = resource;
this.students = students;
} @Override
public int getCount() {
return students.size();
} @Override
public View getView(int position, View convertView, ViewGroup parent) { in = LayoutInflater.from(context);
if (convertView == null) {
Log.d("MyAdapter", "创建新的convertView" + position);
convertView = in.inflate(resource, null);
} else {
Log.d("MyAdapter", "复用原来的convertView" + position);
} TextView name = (TextView) convertView.findViewById(R.id.name);
TextView sex = (TextView) convertView.findViewById(R.id.sex);
TextView Student_id = (TextView) convertView.findViewById(R.id.Student_id);
TextView Myclass = (TextView) convertView.findViewById(R.id.Myclass); Student student = students.get(position); name.setText(student.name);
sex.setText(student.sex);
Student_id.setText(student.Student_id + "");
Myclass.setText(student.aClass.name);
return convertView;
} }
2、在Activity中
List<Student> students=.........
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(new MyAdapter(MainActivity.this, R.layout.list_item, students));
listView.setOnItemClickListener(new OnItemClickListener() { @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), position + "", 0).show(); }
});