Android ApiDemos示例解析(181):Views->Lists->14.Efficient Adapter

上例使用临时数据来绑定列表项解决那些载入费时的列表项在列表滚动时的性能问题,本例介绍如果编写一个高效的List Adapter ,其实也不是什么特别的技术,主要是:

  • 重用getView 传入参数convertView ,避免多次从XML中展开View。
  • 设计了一个ViewHolder,用来存放一个TextView 和ImageView,避免每次都调用findViewById。

说到底就是使用变量把一些本来需要多次调用inflate或是findViewById的对象暂存起来,下次再调用getView时,可以重用这些对象,从而提高getView 的效率。

 public View getView(int position,
 View convertView, ViewGroup parent) {
 // A ViewHolder keeps references to children
 //views to avoid unneccessary calls
 // to findViewById() on each row.
 ViewHolder holder;

 // When convertView is not null, we can reuse
 // it directly, there is no need
 // to reinflate it. We only inflate a new View when
 //the convertView supplied
 // by ListView is null.
 if (convertView == null) {
 convertView = mInflater
 .inflate(R.layout.list_item_icon_text,
 null);

 // Creates a ViewHolder and store references
 //to the two children views
 // we want to bind data to.
 holder = new ViewHolder();
 holder.text
 = (TextView) convertView.findViewById(R.id.text);
 holder.icon
 = (ImageView) convertView.findViewById(R.id.icon);

 convertView.setTag(holder);
 } else {
 // Get the ViewHolder back to get fast
 //access to the TextView
 // and the ImageView.
 holder = (ViewHolder) convertView.getTag();
 }

 // Bind the data efficiently with the holder.
 holder.text.setText(DATA[position]);
 holder.icon.setImageBitmap((position & 1) == 1
 ? mIcon1 : mIcon2);

 return convertView;
}

static class ViewHolder {
 TextView text;
 ImageView icon;
}

这里至少说明了List Adapter的getView 传入的convertView 本身是重用的,而不是每次创建了一个新的convertView。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值