14

R.drawable.*文字列の値に基づいて画像ファイルを動的に読み込みたいとします

これを行う方法はありますか?何かを静的に参照する必要があるようですR.

4

3 に答える 3

22

XML ファイルで画像の ID を宣言しましたか? その場合は、次の方法を使用できます。

res/drawable フォルダーに picture.png があるとします。

アクティビティでは、画像リソースを main.xml ファイルに設定できます

<ImageView android:id="@+id/imageId" android:src="@drawable/picture"></ImageView>

最初のアクティビティで

//to retrieve image using id set in xml.
String imageString = "imageId"
int resID = getResources().getIdentifier(imageString , "id", "package.name");
ImageView image = (ImageView) findViewById(resID);

imageString は動的な名前です。その後、動的リソースの識別子を取得できます。

別の方法、これを行うことができます:

//to retrieve image in res/drawable and set image in ImageView
String imageName = "picture"
int resID = getResources().getIdentifier(imageName, "drawable", "package.name");
ImageView image;
image.setImageResource(resID );

画像リソースを参照し、それに ImageView を設定できます。

于 2011-10-29T20:20:14.710 に答える
9
int drawableId = getResources().getIdentifier(drawablename, "drawable", getPackageName());
imageview.setImageResource(drawableId);

これを試して。これはうまくいくはずです。

于 2011-10-29T20:13:52.623 に答える
1
Class res = R.string.class;
Field field = res.getField("x" + pos);
headerId = field.getInt(null);
header.setText(headerId);

これはドローアブルでも機能します。文字列を編集するだけです。ヘッダー部分は必須ではありません。これは、私が少し前に書いたものから引っ張ってきた単なる例です。

于 2011-10-30T00:06:18.693 に答える