0

我正在制作一个自定义GridView适配器,它设置FrameLayout及其 UI 元素(图像)。适配器本身并不复杂,但我得到了 compile-time error Variable imgThumb have not been initialized更糟糕的是,代码与Google Developer GridView 帮助页面上的代码完全相同。

这是我的适配器:

public class ImageAdapter extends BaseAdapter {
private Context mContext;
private int mGroupId;
private Bitmap[] rescaledImages;
private Integer[] which;

public ImageAdapter(Context c, int groupId) {
    mContext = c;
    mGroupId = groupId;

    //.. do init of rescaledImages array
}

public int getCount() {
    return rescaledImages.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) {
    View frameLayout;
    ImageView imgThumb;

    if (convertView == null) {  // if it's not recycled, initialize some attribute

        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        frameLayout = inflater.inflate(R.layout.group_grid_item, null);
        frameLayout.setLayoutParams(new AbsListView.LayoutParams(130, 130));
        frameLayout.setPadding(0, 10, 0, 10);

        imgThumb = (ImageView) frameLayout.findViewById(R.id.grid_item_thumb);
    } else {
        frameLayout = (FrameLayout) convertView;
    }

    imgThumb.setImageBitmap(rescaledImages[position]); //<-- ERRROR HERE!!!

    return frameLayout;
}
//...

现在,我知道我可以设置方法ImageView imgThumb=null;getView()但我不确定为什么这个示例适用于 Android 开发人员帮助页面。

另外我不确定我是否应该把它imgThumb永远存在null - 这会导致运行时错误吗?

4

3 回答 3

1

该代码与您链接的代码不同,即使您设置了imgThumb = null. 因为在 where 的情况下convertView != nullimgThumb永远不会被设置为任何东西,因此 crash 就行了imgThumb.setImageBitmap(rescaledImages[position]);

于 2013-07-06T08:04:20.840 回答
0

仅当您的 convertView 不为空时才会发生这种情况!因此,您必须在“if”子句之外初始化 imgThumb。

于 2013-07-06T08:00:26.627 回答
0

感谢@LuckyMe(你没有回复整个解决方案)。

无论如何,对于像我一样想要初始化和使用单元GridView格及其子元素的根元素的人,您应该注意在by using方法中默认初始化每个子元素。elseconvertView.findViewById()

即,我的代码必须像这样固定:

if (convertView == null) {  // if it's not recycled, initialize some attribute

    LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    frameLayout = inflater.inflate(R.layout.group_grid_item, null);
    frameLayout.setLayoutParams(new AbsListView.LayoutParams(130, 130));
    frameLayout.setPadding(0, 10, 0, 10);

    imgThumb = (ImageView) frameLayout.findViewById(R.id.grid_item_thumb);
} 
else {
        frameLayout = (FrameLayout) convertView;
        imgThumb = (ImageView) convertView.findViewById(R.id.grid_item_thumb); //INITIALIZE EACH CHILD AS WELL LIKE THIS!!!
    }
于 2013-07-06T09:33:28.393 回答