【Android Training - Performance】提高显示布局文件的性能[Lesson 4 - 使用ViewHolder提升ListView的性能]

Making ListView Scrolling Smooth [使得ListView滚动平滑]

使得滚动ListView平滑的关键在与保持AP的UI thread与复杂的操作隔离。
确保另起一个Thread来处理Disk IO,network access或者SQL access.
为了测试AP的状态,可以enable StrictMode .(Android ICS 4.0上已经默认开启了StrickMode)

Use a Background Thread [使用后台线程]

使用后台线程,这样可以使得UI线程可以专注于描绘UI。
大多数时候,AsycnTask实现了一种简单把需要做的事情与main thread隔离的方法。
[关于如何使用AsyncTask,请参考官方详解,或者参看本人前面一篇文章: 使用AsyncTask来处理一些简单的需要后台处理的动作 ]
下面是一个例子:
// Using an AsyncTask to load the slow images in a background thread
new AsyncTask<ViewHolder, Void, Bitmap>() {
    private ViewHolder v;

    @Override
    protected Bitmap doInBackground(ViewHolder... params) {
        v = params[0];
        return mFakeImageLoader.getImage();
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        super.onPostExecute(result);
        if (v.position == position) {
            // If this item hasn't been recycled already, hide the
            // progress and set and show the image
            v.progress.setVisibility(View.GONE);
            v.icon.setVisibility(View.VISIBLE);
            v.icon.setImageBitmap(result);
        }
    }
}.execute(holder);

从Android 3.0开始,对于AsyncTask有个额外的特色:在多核处理器的情况下,我们可以使用 executeOnExecutor()  来替代execute(),这样系统会根据当前设备的内核数量同时进行多个任务。

Hold View Objects in a View Holder [如何使用View Holder来Hold住view对象]

你的程序在滚动ListView的时候也许会重复频繁的call findViewById(),这样会降低性能。
尽管Adapter会因为循环机制返回一个创建好的View(关于这个机制,请参考鄙人前面的文章: ListView中getView的原理与解决多轮重复调用的方法 )
你仍然需要查找到这些组件并更新它,避免这样的重复,我们可以使用ViewHolder的设计模式。

A ViewHolder对象存放每一个View组件于Layout的tag属性中,因此我们可以立即访问tag中的组件从而避免重复call findViewById()。

下面是定义了一个ViewHolder的例子:
static class ViewHolder {
  TextView text;
  TextView timestamp;
  ImageView icon;
  ProgressBar progress;
  int position;
}
这样之后,我们可以填充这个ViewHolder,并且保存到tag field.
ViewHolder holder = new ViewHolder();
holder.icon = (ImageView) convertView.findViewById(R.id.listitem_image);
holder.text = (TextView) convertView.findViewById(R.id.listitem_text);
holder.timestamp = (TextView) convertView.findViewById(R.id.listitem_timestamp);
holder.progress = (ProgressBar) convertView.findViewById(R.id.progress_spinner);
convertView.setTag(holder);
那么我们就可以直接访问里面的数据了,省去了重复查询,提升了性能。
转载请注明出处:http://blog.csdn.net/kesenhoo,谢谢!


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值