ListView自定义适配器,包括库中的图像

问题描述 投票:0回答:1

在创建自定义ListView适配器时,通常我会从Array Adapter<String>扩展它,但我想制作一个ListView,其中包含手机图库中的照片。

我设法从画廊获取Bitmap指的是用户选择的图片并将其放入常规的ImageView但是,我真的不知道怎么做ListView的适配器显示用户选择的照片。照片是Bitmap,任何帮助?

android listview android-listview imageview custom-adapter
1个回答
1
投票

您可以像对包含文本的列表一样完成此操作。

首先,您可能想要创建一个表示列表中项目的类(可能您想要添加更多数据,如ID或名称),例如:

class ItemInMyList {
        Bitmap image;
        String title;
        Integer id;
 }

然后只需创建一个扩展ArrayAdapter的新类:

public class MyAdapter extends ArrayAdapter<ItemInMyList> {
    private final Context context;
    private final List<ItemInMyList> values;
    private int layout;

    public MyAdapter(Context context, List<ItemInMyList> values, int layout) {
        super(context, layout, values);
        this.context = context;
        this.values = values;
        this.layout = layout;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        // When convertView is not null, we can reuse it directly, there is no need
        // to reinflate it. We only inflate a new View when the convertView supplied
        // by ListView is null.
        if (convertView == null) {
            convertView = inflater.inflate(layout, null);
            // Creates a ViewHolder and store references to the two children views
            // we want to bind data to.
            holder = new ViewHolder();
            holder.name= (TextView) convertView.findViewById(R.id.name);
            holder.image = (ImageView) convertView.findViewById(R.id.image);
            // Bind the data efficiently with the holder.
            convertView.setTag(holder);
        } else {
            // Get the ViewHolder back to get fast access to the TextView
            // and the ImageView.
            holder = (ViewHolder) convertView.getTag();
        }
        try {
            holder.text.setText(values.get(position).title);
            // Set your image to the ImageView in your list layout
            holder.image.setImageBitmap(values.get(position).image);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        return convertView;
    }

    static class ViewHolder {
        TextView name;
        ImageView image;
    }
}

现在,您只需创建一个表示ListView中一行的布局。在此示例中,您可能会将ImageView(图像)和TextView(名称)添加到LinearLayout。

然后,当您实例化适配器时,只需为其指定行的布局:

new MyAdapter(this, data, R.layout.rowlayout);

就是这样,基本上。

© www.soinside.com 2019 - 2024. All rights reserved.