Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

java - 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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

For more, see this and this and this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...