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中顯示圖片了。