您可以像处理仅包含文本的列表一样执行此操作。
首先,您可能想要创建一个代表列表中项目的类(也许您想要添加更多数据,例如 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);
基本上就是这样。