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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2021-03-18 我要评论
想了解Android中 自定义数据绑定适配器BaseAdapter的方法的相关内容吗,在本文为您仔细讲解Android BaseAdapter的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,BaseAdapter,下面大家一起来学习吧。

复制代码 代码如下:

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;
 }
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们