gridview顯示圖片的方法是什么

小億
96
2023-12-11 23:35:42

GridView顯示圖片的方法可以通過(guò)以下步驟實(shí)現(xiàn):

  1. 在布局文件中添加GridView控件:
<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"
/>
  1. 創(chuàng)建一個(gè)適配器類來(lái)提供數(shù)據(jù)給GridView:
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;
    }
}
  1. 在Activity中設(shè)置適配器并將其與GridView關(guān)聯(lián)起來(lái):
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中顯示圖片了。

0