1.简单适配器
private void show() {
List<Person> persons = personService.getScrollData(0, 20);//listView存放的数据
List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
for(Person person : persons){
HashMap<String, Object> item = new HashMap<String, Object>();
item.put("name", person.getName());
item.put("phone", person.getPhone());
item.put("amount", person.getAmount());
item.put("id", person.getId());
data.add(item);
}
SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,
new String[]{"name", "phone", "amount"}, new int[]{R.id.name, R.id.phone, R.id.amount});
listView.setAdapter(adapter);
}
2.结果集适配器
public class PersonAdapter extends BaseAdapter {
private List<Person> persons;//在绑定的数据
private int resource;//绑定的条目界面
private LayoutInflater inflater;
}
private void show2() {
Cursor cursor = personService.getCursorScrollData(0, 20);//listView存放的数据
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item, cursor,
new String[]{"name", "phone", "amount"}, new int[]{R.id.name, R.id.phone, R.id.amount});
listView.setAdapter(adapter);
}
3.自定义适配器
//自定义适配器
private void show3() {
List<Person> persons = personService.getScrollData(0, 20);//listView存放的数据
PersonAdapter adapter = new PersonAdapter(this, persons, R.layout.item);
listView.setAdapter(adapter);
}
自定义适配器中的PersonAdapetr
public PersonAdapter(Context context, List<Person> persons, int resource) {
this.persons = persons;//数据源,listView要放的数据
this.resource = resource;//每个条目的View的界面id
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return persons.size();//数据总数
}
@Override
public Object getItem(int position) {
return persons.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView nameView = null;
TextView phoneView = null;
TextView amountView = null;
if(convertView==null){//条目重用
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.nameView = nameView;
cache.phoneView = phoneView;
cache.amountView = amountView;
convertView.setTag(cache);
}else{
ViewCache cache = (ViewCache) convertView.getTag();
nameView = cache.nameView;
phoneView = cache.phoneView;
amountView = cache.amountView;
}
Person person = persons.get(position);
//下面代码实现数据绑定
nameView.setText(person.getName());
phoneView.setText(person.getPhone());
amountView.setText(person.getAmount().toString());
return convertView;
}
private final class ViewCache{
public TextView nameView;
public TextView phoneView;
public TextView amountView;
}
}