複製代碼 代碼如下:public class PersonAdapter extends
BaseAdapter {
private List persons;// 要繫結資料
private int resource;// 綁定的一個條目介面的id,此例中即為item.xml
private LayoutInflater inflater;// 布局填充器,它可以使用一個xml檔案產生一個View對象,可以通過Context擷取執行個體對象
public PersonAdapter(Context context, List persons, int resource) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.resource = resource;
this.persons = persons;
}
@Override
public int getCount() {// 得到要繫結資料總數
return persons.size();
}
@Override
public Object getItem(int position) {// 給定索引值,得到索引值對應的對象
return persons.get(position);
}
@Override
public long getItemId(int position) {// 擷取條目id
return position;
}
// ListView有緩衝功能,當顯示第一頁頁面時會建立頁面對象,顯示第二頁時重用第一頁建立好了的對象
// 取得條目介面:position代表當前條目所要繫結資料在集合中的索引值
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView nameView = null;
TextView phoneView = null;
TextView amountView = null;
if (convertView == null) {// 顯示第一頁的時候convertView為空白
convertView = inflater.inflate(resource, null);// 產生條目對象
nameView = (TextView) convertView.findViewById(R.id.name);
phoneView = (TextView) convertView.findViewById(R.id.phone);
amountView = (TextView) convertView.findViewById(R.id.amount);
ViewCache cache = new ViewCache();
cache.amountView = amountView;
cache.nameView = nameView;
cache.phoneView = phoneView;
convertView.setTag(cache);
} else {
ViewCache cache = (ViewCache) convertView.getTag();
amountView = cache.amountView;
nameView = cache.nameView;
phoneView = cache.phoneView;
}
Person person = persons.get(position);
// 實現資料繫結
nameView.setText(person.getName());
phoneView.setText(person.getPhone());
amountView.setText(person.getAmount());
return convertView;
}
private final class ViewCache {
public TextView nameView;
public TextView phoneView;
public TextView amountView;
}
}