【问题标题】:Android GridView AdapterAndroid GridView 适配器
【发布时间】:2014-06-20 09:12:11
【问题描述】:

为 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
}

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

【问题讨论】:

  • What if I want several items to display the same picture ? 请详细说明。

标签: java android gridview imageview adapter


【解决方案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
}

【讨论】:

  • 如果创建多个数组,getCount()中如何返回所选数组的长度?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多