Android GridView适配器

时间:2014-06-20 09:12:12

标签: java android gridview imageview adapter

为GridView创建适配器时,如下所示:

public class ImageAdapter extends BaseAdapter {
private Context mContext;

public ImageAdapter(Context c) {
    mContext = c;
}

public int getCount() {
    return mThumbIds.length;
}

public Object getItem(int position) {
    return null;
}

public long getItemId(int position) {
    return 0;
}

// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;
    if (convertView == null) {  // if it's not recycled, initialize some attributes
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
    } else {
        imageView = (ImageView) convertView;
    }

    imageView.setImageResource(mThumbIds[position]);
    return imageView;
}

// references to our images
private Integer[] mThumbIds = {
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7
}

适配器如何知道它必须在屏幕上显示多少项?如果我想要几个项目显示相同的图片怎么办? 感谢。

1 个答案:

答案 0 :(得分:1)

getCount方法返回的计数是适配器要显示的项目数

public int getCount() {
    return mThumbIds.length;
}

如果您想要多个项目显示相同的图像,请创建不同的图像数组,重复一些图像,并返回该数组的长度。

例如:

// references to our images
private Integer[] mThumbIds = {
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_5, R.drawable.sample_5
        R.drawable.sample_6, R.drawable.sample_7,
        R.drawable.sample_7, R.drawable.sample_7
}