GridView顯示圖片的方法可以通過(guò)以下步驟實(shí)現(xiàn):
<GridView
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:columnWidth="100dp"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private int[] mImages;
public ImageAdapter(Context context, int[] images) {
mContext = context;
mImages = images;
}
@Override
public int getCount() {
return mImages.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(100, 100));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mImages[position]);
return imageView;
}
}
GridView gridView = findViewById(R.id.gridview);
int[] images = {R.drawable.image1, R.drawable.image2, R.drawable.image3}; // 圖片資源數(shù)組
ImageAdapter adapter = new ImageAdapter(this, images);
gridView.setAdapter(adapter);
這樣就可以在GridView中顯示圖片了。