2011-09-25 15 views
16

イメージの名前を持つデータベースがあるため、R.drawable.myimageではなく変数を使用します。私はデータベースから名前を取得し、私はこの名前でdrawableリソースを使いたいと思います。変数を使用した描画可能リソース

String flagimage = "R.drawable." + myHelper.getFlagImage(5); 
int resourceId = Integer.parseInt(flagimage); 
Bitmap flag = BitmapFactory.decodeResource(getResources(), resourceId); 

答えて

36

あなたは上記の機能はR.drawable.usと同じ整数値を返します

getIdentifier (String name, String defType, String defPackage);

getResources().getIdentifier("us","drawable","com.app"); 

のようなリソースの名前を使用することができます。

これは、リソース名でアクセスする方法です。あなたがIDを取得するには、このコードを使用することができます

+0

ちょうど簡単なメモ[getIdentifier](http://developer.android.com/reference/android/contentあなたにたくさん – Alex

+2

に感謝します/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29)は、そのようなリソースが見つからない場合に「0」を返します。 (0は有効なリソースIDではありません) – razzak

16

...

Resources res = this.getResources(); 
int resID = res.getIdentifier(imagename, "drawable", this.getPackageName()); 
+0

検索のあと、それは素晴らしいことです。ありがとう –

関連する問題