温馨提示×

gridview如何显示图片

小亿
118
2023-08-14 09:29:00
栏目: 编程语言

GridView可以通过使用ImageAdapter来显示图片。首先,在xml布局文件中,添加一个GridView组件:

<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>

接下来,在java代码中,创建一个ImageAdapter类,继承自BaseAdapter,并重写相关方法:

public class ImageAdapter extends BaseAdapter {
private Context mContext;
private List<Drawable> mImages;
public ImageAdapter(Context context, List<Drawable> images) {
mContext = context;
mImages = images;
}
@Override
public int getCount() {
return mImages.size();
}
@Override
public Object getItem(int position) {
return mImages.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageDrawable(mImages.get(position));
return imageView;
}
}

最后,在Activity中设置GridView的适配器:

GridView gridView = findViewById(R.id.gridView);
List<Drawable> images = new ArrayList<>();
// 添加图片到images列表
ImageAdapter imageAdapter = new ImageAdapter(this, images);
gridView.setAdapter(imageAdapter);

通过将图片添加到images列表,并设置适配器,就可以在GridView中显示图片了。

0