2012-03-04 11 views
6

私はカスタムカーソルアダプタを持っており、イメージをListViewのImageViewに配置したいと思います。名前でリソースイメージをカスタムカーソルアダプタに取得

私のコードは次のとおりです。

public class CustomImageListAdapter extends CursorAdapter { 

    private LayoutInflater inflater; 

    public CustomImageListAdapter(Context context, Cursor cursor) { 
    super(context, cursor); 
    inflater = LayoutInflater.from(context); 
    } 

    @Override 
    public void bindView(View view, Context context, Cursor cursor) { 
    // get the ImageView Resource 
    ImageView fieldImage = (ImageView) view.findViewById(R.id.fieldImage); 
    // set the image for the ImageView 
    flagImage.setImageResource(R.drawable.imageName); 
    } 

    @Override 
    public View newView(Context context, Cursor cursor, ViewGroup parent) { 
    return inflater.inflate(R.layout.row_images, parent, false); 
    } 
} 

これは、すべてOKですが、私は、データベース(カーソル)からの画像の名前を取得したいと思います。 私は

String mDrawableName = "myImageName"; 
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName()); 

と試みたが、エラーが返されます:あなたが唯一のContextオブジェクトにgetResources()通話を行うことができます

+0

なぜカーソルから取得したいのですが、代わりに 'cursor.getString'を呼び出しません。あなたの画像はどこに保存されていますか? –

答えて

13

「メソッドgetResources()は、タイプCustomImageListAdapterについて定義されていません」。 CursorAdapterのコンストラクタはそのような参照を取るので、それを追跡して(おそらく)bindView(...)で使用できるようにクラスメンバを作成するだけです。あなたはおそらくgetPackageName()のためにそれを必要とします。

private Context mContext; 

public CustomImageListAdapter(Context context, Cursor cursor) { 
    super(context, cursor); 
    inflater = LayoutInflater.from(context); 
    mContext = context; 
} 

// Other code ... 

// Now call getResources() on the Context reference (and getPackageName()) 
String mDrawableName = "myImageName"; 
int resID = mContext.getResources().getIdentifier(mDrawableName , "drawable", mContext.getPackageName()); 
+0

+1あなたは私にそれを打つ。 :) – Squonk

+0

"MH"に感謝します。ソリューションのために。 (MisterSquonkにも) – Cuarcuiu

+0

アクティビティ内にコンテキストを追加せずにgetResources()を使用できるのはなぜですか?ありがとう。 – Ricardo

関連する問題