创建自定义ListView
适配器时,通常我会从Array Adapter<String>
扩展它,但我想在手机图库中制作包含照片的ListView
。
我设法从图库中获取Bitmap
引用用户选择的图片并将其放入普通ImageView
但是,我真的不知道怎么做适配器ListView
显示用户选择的照片。照片是Bitmap
,有什么帮助?
答案 0 :(得分: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);
基本上就是这样。