-2

我无法在 gridview 上加载图像,它总是崩溃。记录猫消息“ArrayIndexOutOfBoundsException length=16; index=16”
这是我的代码:

public Integer[] mThumbIds = {
        R.drawable.pic_1, R.drawable.pic_2,
        R.drawable.pic_3, R.drawable.pic_4,
        R.drawable.pic_5, R.drawable.pic_6,
        R.drawable.pic_7, R.drawable.pic_8,
        R.drawable.pic_9, R.drawable.pic_10,
        R.drawable.pic_11, R.drawable.pic_12,
        R.drawable.pic_13, R.drawable.pic_14,
        R.drawable.pic_15, R.drawable.pic_16,
        R.drawable.pic_17, R.drawable.pic_18,
        R.drawable.pic_19, R.drawable.pic_20,
        ........ R.drawable.pic_96 
        };

代码 :

@Override
public View getView(int position, View convertView, ViewGroup parent) { 

    int width = metrics.widthPixels / 6;
    int height = metrics.heightPixels / 6;

    ImageView i;     
        i = new ImageView(mContext);
        i.setLayoutParams(new GridView.LayoutParams(height, height));
        i.setScaleType(ImageView.ScaleType.CENTER_CROP);                         
    }

    if(mImageSet == IMAGE_SET_ONE) {           
        Integer[] images1 = new Integer[16];         
        System.arraycopy(mThumbIds, 0, images1, 0, 16);    
        i.setImageResource(images1[position]);
    } else if(mImageSet == IMAGE_SET_THREE) {

    ...........    
 }

    return i;       
}

请帮我..

4

3 回答 3

2

我建议的一件事是,确保在以下方法position中小于mThubIds数组长度。数组索引从零开始,如果位置大于(或)等于mThumbIds长度,你会得到ArrayIndexOutofBoundsException.

@Override
public Object getItem(int position) {
    return mThumbIds[position];
}

例子:

 @Override
    public Object getItem(int position) {
        if(position < mThumbIds.length){
        return mThumbIds[position];
        }
      return null;
    }
于 2013-07-22T14:56:13.303 回答
0
@Override
public Object getItem(int position) {
    if(position >= mThumbIds.length) return null;
    return mThumbIds[position];
}

请为使用匈牙利符号而开枪。

于 2013-07-22T14:57:48.980 回答
0
Integer[] images1 = new Integer[16];         
System.arraycopy(mThumbIds, 0, images1, 0, 16);    
i.setImageResource(images1[position]);

Integer您从mThumbIds内部复制前 16 个images1,但由于mThumbIds包含 16 个以上的元素,您position可以假定一个介于 0 和mThumbIds.lenght - 1. 当位置为 16 时,您将获得ArrayIndexOutofBoundsException. You should use i.setImageResource(mThumbIds[position]);

于 2013-07-22T15:04:43.900 回答