在Adapter中使用getView方法的优化方法

时间:2015-03-14 18:40:38

标签: android android-listview android-arrayadapter listadapter

据我所知,每次调用view.findViewById(R.id.title);是非常昂贵的操作。如何通过存储这些int值来优化它。在List Adapter中使用的优化方法是什么?

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        final DataObject dataObject = getItem(position);
        if (view == null) {
        // No view created yet
        LayoutInflater layoutInflater = LayoutInflater.from(getContext());
        view = layoutInflater.inflate(layoutResourceId, parent, false);
        }
        if (view != null) {
        TextView title = (TextView) view.findViewById(R.id.title);
        TextView price = (TextView) view.findViewById(R.id.price);
        ImageView img = (ImageView) view.findViewById(R.id.profile_pic);
        RatingBar overallRating = (RatingBar)                                                 view.findViewById(R.id.overall_rating);

1 个答案:

答案 0 :(得分:1)

你应该使用这样的视图:

ViewHolder holder;

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    if (convertView == null) {
        holder = new ViewHolder();
        convertView = inflater.inflate(R.layout.chocolate_list_item,
                parent, false);
        holder.txtvwChocolateName = (TextView) convertView
                .findViewById(R.id.xtxtvwChocolateName);
        holder.imgvwChocolateIcon=(ImageView)convertView.findViewById(R.id.ximgvwChocolateIcon);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.txtvwChocolateName.setText(alChocolate.get(position)
            .getStrChocolateName());
    holder.imgvwChocolateIcon.setImageResource(images[position]);
    return convertView;
}

class ViewHolder {
    TextView txtvwChocolateName;
    ImageView imgvwChocolateIcon;
}