包含来自图库的图像的 ListView 自定义适配器

ListView Custom Adapter that includes Images from gallery

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

我设法从图库中获取了 Bitmap 参考用户选择的图片并将其放入常规 ImageView 但是,我真的不知道如何做一个适配器a ListView 显示用户选择的照片。照片是Bitmap,有什么帮助吗?

您可以像处理仅包含文本的列表一样执行此操作。

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

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

然后创建一个新的 class 扩展 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 中的一行。在此示例中,您可能会向 LinearLayout 添加一个 ImageView(图像)和一个 TextView(名称)。

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

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

基本上就是这样。