Dynamically get drawables by ID

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Dynamically get drawables by ID



I want to take a byte and append it to a resource ID to be able to get the image that corresponds to that numbered deck in the game. It was easy to with paths on other devices, but with the Resource ID's I am unsure how I could go about do this.


byte



Here's what I have now:


switch(GameSettings.gameDeck)

case 1:
deckImage.setBackgroundResource(R.drawable.deck1);
break;
case 2:
deckImage.setBackgroundResource(R.drawable.deck2);
break;
case 3:
deckImage.setBackgroundResource(R.drawable.deck3);
break;
case 4:
deckImage.setBackgroundResource(R.drawable.deck4);
break;



In my Blackberry version of this, I simply had:


deckImage.setBitmap(Bitmap.getBitmapResource("/path/deck" + GameSettings.gameDeck + ".png"));



Is there a way to accomplish something similar using Resource IDs on Android?




1 Answer
1



Use getResources().getIdentifier() from your Context (e.g., Activity), but please cache the result if you will use it more than once. getIdentifier() is implemented on Resources.


getResources().getIdentifier()


Context


Activity


getIdentifier()


Resources



For example:


int drawableId=getResources().getIdentifier("foo"+index, "drawable", getPackageName());



would return the value of R.drawable.fooN, where N is the number given by index.


R.drawable.fooN


N


index



For more, see this and this and this.





Awesome, that works perfectly. Thanks!
– Matt Swanson
Mar 10 '10 at 3:11





To improve on this answer: Bitmap myImage = BitmapFactory.decodeResource(getResources(), R.drawable.myImageName);
– RockMeetHardplace
Dec 3 '11 at 17:23





How would you recommend caching, LruCache?
– theblang
Jul 2 '14 at 16:06





@mattblang: IDs are only ints, and you shouldn't have millions of IDs. Hence, plain data members (or even local variables outside of loops) should suffice in most cases.
– CommonsWare
Jul 2 '14 at 16:18





@CommonsWare Sorry, I meant the drawables.
– theblang
Jul 2 '14 at 16:19






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS