Java 通过 ID 动态获取可绘制对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2414134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:18:03  来源:igfitidea点击:

Dynamically get drawables by ID

javaandroid

提问by Matt Swanson

I want to take a byteand 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.

我想将 abyte附加到资源 ID 上,以便能够获得与游戏中该编号牌组对应的图像。使用其他设备上的路径很容易,但是使用资源 ID 我不确定我该如何去做。

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?

有没有办法在 Android 上使用资源 ID 来完成类似的事情?

采纳答案by CommonsWare

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 Nis the number given by index.

将返回 的值R.drawable.fooN,其中N是 给出的数字index

For more, see thisand thisand this.

有关更多信息,请参阅thisthis以及this