我想用自定义对象Person
填充列表活动类,我写了以下代码
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
liPerson = new ArrayList<Person>();
person = new Person("Pritom Kumar Mondal", "Software Engineer", "bd");
liPerson.add(person);
person = new Person("Pritom Kumar Mondal", "Software Engineer", "bd");
liPerson.add(person);
person = new Person("Pritom Kumar Mondal", "Software Engineer", "bd");
liPerson.add(person);
person = new Person("Pritom Kumar Mondal", "Software Engineer", "bd");
liPerson.add(person);
Person[] persons = (Person[]) liPerson.toArray();
setListAdapter(new MyAdapter(this,
android.R.layout.simple_list_item_1,
persons));
}
private class MyAdapter extends ArrayAdapter<Person> {
private Person[] persons;
public MyAdapter(Context context, int resource, Person[] persons) {
super(context, resource, persons);
// TODO Auto-generated constructor stub
this.persons = persons;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_item, parent, false);
//String[] items = getResources().getStringArray(R.array.countries);
Person p = persons[position];
ImageView iv = (ImageView) row.findViewById(R.id.imageView1);
TextView tv = (TextView) row.findViewById(R.id.textView1);
tv.setText(p.getName());
String mDrawableName = "bd";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
iv.setImageResource(resID);
return row;
}
}
它不起作用。我可以从我的xml文件中填充列表活动,但我想将它作为我的自定义对象。
答案 0 :(得分:1)
将整个ArrayList传递给ArrayAdapter。然后,您可以使用getItem(position)获取您的对象。“您的方法在这里”
ArrayList<Person> personList = new ArrayList<Person>();
ArrayAdapter<Person> adapter = new ArrayAdapter<Person>(this,
R.layout.person_item, personList) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
if (null == convertView) {
row = mInflater.inflate(R.layout.person_item, null);
} else {
row = convertView;
}
TextView tView = (TextView) row.findViewById(R.id.tvName);
tView.setText(getItem(position).getName()); // This is where you get the name from your object
return row;
}
};