900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > Android中 自定义数据绑定适配器BaseAdapter的方法

Android中 自定义数据绑定适配器BaseAdapter的方法

时间:2023-11-23 23:14:41

相关推荐

Android中 自定义数据绑定适配器BaseAdapter的方法

今天小编要跟大家分享Android中 自定义数据绑定适配器BaseAdapter的方法,精心挑选的过程简单易学,喜欢的朋友一起来学习吧!

代码如下:

public class PersonAdapter extendsBaseAdapter {

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;

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。