为什么我在GridView自定义适配器中收到“ImageView未初始化”错误?

问题描述 投票:0回答:3

我正在制作一个自定义GridView适配器,它设置FrameLayout及其UI alements(图像)。适配器本身并不复杂,但我得到编译时错误Variable imgThumb have not been initialized。更糟糕的是,代码与Google Developer GridView help page完全相同。

这是我的适配器:

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 - 这可以导致运行时错误?

android android-gridview baseadapter android-adapter
3个回答
1
投票

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


0
投票

只有当您的convertView不为null时才会发生这种情况!所以,你必须在'if'子句之外初始化imgThumb。


0
投票

得到了@LuckyMe(你没有回复整个解决方案)。

无论如何,对于那些喜欢我想要初始化并使用GridView单元及其子元素的根元素的人,你应该注意默认使用else方法初始化convertView.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!!!
    }
© www.soinside.com 2019 - 2024. All rights reserved.