Android ViewHolder 优化 ListView
NellPhipps
9年前
来自: http://blog.csdn.net//never_cxb/article/details/48164541
ViewHolder 优化 ListView
参见这篇博客, 里面介绍了Android ListView 基础入门 简介以及深入优化
ViewHolder介绍
A ViewHolder object stores each of the component views inside the tag field of the Layout, so you can immediately access them without the need to look them up repeatedly. First, you need to create a class to hold your exact set of views.
意思就是 ViewHolder 存储了一些组件如 TextView ImageView 等等, 下次使用无需这样寻找
(TextView) convertView.findViewById(R.id.text)
源代码
package com.example.tomchen.testlistview; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.List; /** * Created by tomchen on 9/1/15. */ public class IconAdapter extends ArrayAdapter<Icon> { private int resourceId; public IconAdapter(Context context, int resource, List<Icon> icons) { super(context, resource, icons); this.resourceId = resource; } @Override public View getView(int position, View convertView, ViewGroup parent) { Icon icon = getItem(position); View view; ViewHolder viewHolder = new ViewHolder(); if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(resourceId, null); ImageView image = (ImageView) convertView.findViewById(R.id.icon); TextView text = (TextView) convertView.findViewById(R.id.text); viewHolder.imageView = image; viewHolder.textView = text; convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.imageView.setImageResource(icon.getImageId()); viewHolder.textView.setText(icon.getName()); return convertView; } class ViewHolder { private TextView textView; private ImageView imageView; } }
Note
在getView(int position, View convertView, ViewGroup parent)
中复用了变量convertView