19

現在、次のように Android アプリケーションで PNG 画像を描画しています。

ImageView image = new ImageView(context);
image.setImageDrawable(context.getResources().getDrawable(R.drawable.testimage))

データベースに画像名のリストがある場合、画像名を使用して上記のドローアブルを設定する方法はありますか? データベースを通過するコードは既にあります。ここから取得した値に基づいて画像を描画しようとしています。

たとえば、DB のレコード:

ID:    Name:    ImageName:
-      Test     testimage

したがって、このレコードを読んでいるとき、「testimage」という値の文字列があり、画像ドローアブルを に設定したいと思いR.drawable.testimageます。

私がそれを行うことを考えていた1つの方法は、次のようなものになるでしょう:

int image = R.drawable.blank; // blank image

// testimage.png is the image name from the database
if(imageName.toString().equals("testimage.png"))
    image = R.drawable.testimage;
else if(imageName.toString().equals("another.png"))
    image = R.drawable.another;
else if(imageName.toString().equals("etc.png"))
    image = R.drawable.etc;

ただし、これはあまり効率的ではありません。

ありがとう

4

4 に答える 4

26

これを行う方法があります。Resources.getIdentifier()http://developer.android.com/reference/android/content/res/Resources.htmlを使用して、文字列でリソースIDを取得できます。

何かのようなもの:

int resourceId = Activity.getResources().getIdentifier("testimage", "drawable", "your.package.name");
于 2010-11-30T11:10:13.100 に答える
22

私は使用しています:

int resId = getResources().getIdentifier("testimage", "drawable", getPackageName());
image.setImageResource(resId);

"testimage" - たとえば、testimage.jpg に対応します。つまり、".jpg" は含めないでください。

"drawable" - @drawable/testimage のようなリソース タイプです。

Resources.getIdentifier(...) を確認してください

于 2010-11-30T11:15:57.390 に答える
0

画像を assets/ フォルダーに入れて開きます

image.setImageURI("file:///android_asset/" + nameFromDB);
于 2010-11-30T11:18:29.393 に答える
-2

文字列パス = "sdcard/camera_app/name.jpg"; img.setImageDrawable(Drawable.createFromPath(パス));

于 2016-08-02T18:19:51.257 に答える