0

UI 要素 (画像)を設定するカスタムGridViewアダプターを作成しています。FrameLayoutアダプター自体は複雑ではありませんが、コンパイル時エラーが発生します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。が何convertView != nullimgThumbも設定されないため、行でクラッシュするためimgThumb.setImageBitmap(rescaledImages[position]);です。

于 2013-07-06T08:04:20.840 に答える
0

これは、convertView が null でない場合にのみ発生します! そのため、'if' 句の外で imgThumb を初期化する必要があります。

于 2013-07-06T08:00:26.627 に答える
0

@LuckyMeのおかげでそれを手に入れました(彼はソリューション全体に返信しませんでした)。

とにかく、私のようにセルのルート要素とその子要素を初期化して使用したい場合は、by usingメソッドで各子要素GridViewをデフォルトで初期化するように注意する必要があります。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 に答える