1.2ListView优化之Viewholder

//
本篇是通用版的listView的优化,最终会使用模板设计模式和钩子方法对通用优化,在进行代码层级的深度优化。
//

本篇研究listView的第二项优化:

使用ViewHolder  存储findViewById得到的控件对象。避免重复的findViewById。findViewById会走遍历查找,也是比较消耗内存的一项操作。

通用版listView的adapter的使用,核心代码如下:
/getView优化//
//基本优化:
//①使用convertView重用,避免每次getView方法的时候,都去创建新的View
//②使用ViewHolder来临时存储item中的控件,避免出现重复多次的findViewById,此操
//作也是消耗内存的操作
//③ListView的在布局中,不要设置自适应(wrap_content),这样会导致getView方法的重
//调用
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder = null;
if (convertView == null) {
        viewHolder = new ViewHolder();
        convertView = mInflater.inflate(R.layout.lv_books_items, parent, false);
        viewHolder.tv_desc = (TextView) convertView.findViewById(R.id.tv_desc);
        viewHolder.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
        viewHolder.tv_price = (TextView) convertView.findViewById(R.id.tv_price);
//setTag方法学习
stu4ViewPsetTag();
        convertView.setTag(viewHolder);

    }else{
        viewHolder=(ViewHolder)convertView.getTag();
    }
    Log.e("convertView","当前的position:"+position+"当前的对象:"+convertView.toString());
return convertView;
}
class ViewHolder {
private TextView tv_title;
private TextView tv_desc;
private TextView tv_price;
}
在前一篇中,我们理解了复用的convertView,对listView的性能进行了优化。
核心在重用了convertView对象。但是,即使重用了convertView对象,google 2010年大会上分享的第二种写法,仍然存在着每次getView的时候,会进行重复的findViewById。那么能不能通过一种方式把已经findViewById的结果直接保存在复用的对象中。


那么View.setTag方法,就能实现这个功能,而且不需要额外的数据结构。
在使用重用的ConvertView的时候,只需要通过convertView.getTag方式就获得绑定的tag对象。

就有了如上的实现方式。

在如上的代码注释中提到③中优化,是通过布局优化。是基于view绘制的的原理,避免过多重复的计算。则一般要求是固定高度的ListView或者填充父窗体。一定不能使用wrap_content.

补充说明对View.setTag(Object obj)的理解:
/*****************************setTag方法理解******************************/
//Sets the tag associated with this view. A tag can be used to mark a view
//in its hierarchy and does not have to be unique within the hierarchy.
//Tags can also be used to store data within a view without resorting to
//another data structure.
//中文:设置一个和当前View关联的标记。这个标记可以用来标示一个view在它的层级中
//但是有不要求其在层级中的唯一性。同时标记可以在View内部用于存储数据而无需重新
//存储另一个数据结构
/************************************************************************/


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hymKing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值