edo1z blog

プログラミングなどに関するブログです

Android - ViewHolder

ListViewの効率化をViewHolderでします。 adapter使うときに、Viewが行ごとに変わりますが、かといって毎回findViewByIdやると効率が悪いので、viewHolderを使うといいらしいです。viewHolderは、各行用のviewの要素を覚えておいてくれるやつでっす。

ViewHolder使わない場合のコード

public class MyAdapter extends ArrayAdapter<Food> {
    private final LayoutInflater _inflater;

    public MyAdapter(Context context, List<Food> objects) {
        super(context, 0, objects);
        _inflater = LayoutInflater.from(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView == null) {
            convertView = _inflater.inflate(R.layout.row, parent, false);
        }
        Food food = super.getItem(position);
        ((TextView)convertView.findViewById(R.id.text_name)).setText(food.name);
        ((TextView)convertView.findViewById(R.id.text_price)).setText(String.valueOf(food.price));
        return convertView;
    }
}

ViewHolder使った場合のコード

public class MyAdapter extends ArrayAdapter<Food> {
    private final LayoutInflater _inflater;

    public MyAdapter(Context context, List<Food> objects) {
        super(context, 0, objects);
        _inflater = LayoutInflater.from(context);
    }

    private static class ViewHolder {
        TextView name;
        TextView price;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View cv = convertView;
        ViewHolder vh = null;
        if(cv == null) {
            cv = _inflater.inflate(R.layout.row, parent, false);
            vh = new ViewHolder();
            vh.name = (TextView)cv.findViewById(R.id.text_name);
            vh.price = (TextView)cv.findViewById(R.id.text_price);
            cv.setTag(vh);
        } else {
            vh = (ViewHolder)cv.getTag();
        }
        Food food = super.getItem(position);
        vh.name.setText(food.name);
        vh.price.setText(String.valueOf(food.price));
        return cv;
    }
}