优化android的listview的性能

ListView在android里面用的很广泛,可是拖动的时候,总是感觉有延迟。如何才能实现listview的平滑滚动呢?看了android的一些文档,介绍如何优化,这里有一篇文章http://developer.android.com/training/improving-layouts/smooth-scrolling.html

总体上来说,有2点:

1. 将一些耗时的操作用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);

2. 优化adapter的getView的操作:

static class ViewHolder {
    TextViewtext;
    ImageViewicon;
}

public View getView(intposition, ViewconvertView, ViewGroupparent) {
    ViewHolderholder;
    if (convertView == null) {
        5convertView = mInflater.inflate(R.layout.list_item_icon_text, null);

        holder = new ViewHolder();
        holder.text = (TextView) convertView.findViewById(R.id.text);
        holder.icon = (ImageView) convertView.findViewById(R.id.icon);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.text.setText(DATA[position]);
    holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);

    returnconvertView;
}

 

Print Friendly

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>