listview添加图片
时间: 2023-09-30 18:10:32 浏览: 135
在ListView中添加图片可以使用自定义适配器。首先,你需要创建一个继承自BaseAdapter的适配器类,并在getView方法中实现图片的加载。在getView方法中,你可以使用ImageView来显示图片,并通过设置ImageView的setImageResource或setImageBitmap方法来加载图片。最后,将该适配器设置到ListView中,通过setAdapter方法。
代码示例:
```
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context context) {
mContext = context;
}
@Override
public int getCount() {
return mThumbIds.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable
阅读全文