GridView可以通过使用ImageAdapter来显示图片。首先,在xml布局文件中,添加一个GridView组件:
```xml
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,并重写相关方法:
```java
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private List
public ImageAdapter(Context context, List
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的适配器:
```java
GridView gridView = findViewById(R.id.gridView);
List
// 添加图片到images列表
ImageAdapter imageAdapter = new ImageAdapter(this, images);
gridView.setAdapter(imageAdapter);
```
通过将图片添加到images列表,并设置适配器,就可以在GridView中显示图片了。