问题
I have 718 drawables in the drawable-mdpi
, drawable-hdpi
and drawable-xhdpi
folders, whose names are 1.png, 2.png... to 718.png. (They are actually Pokémon sprites)
So, depending on the Pokémon, I want to load one of them to show it. However, I cannot use the number to directly identify the R drawable ID.
Is there any way (besides of a 718-case switch or a Hashmap<Integer,Integer>
) to somehow link the int IDs to the R drawable IDs?
回答1:
You could try:
String sprite = "drawable/"+number;
int imageResource = getResources().getIdentifier(sprite, null, getPackageName());
The drawable
is the folder where the image is in. The number
is the number of the image you want. e.g. 1.png
回答2:
Name the Drawables
as image_1.png ..to.. image_718.png.
Using getIdentifier
you can get the drawable resource Id like this.
int resourceId = getResources().getIdentifier("image_1", "drawable", getPackageName());
回答3:
use a TypedArray
to define the images in an array resource. then you can load the resource and get the resources as offsets. It will be significantly faster than using getIdentifier(). Note that I added a 0.png drawable, so the array indices would match your numeric values.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="icons">
<item>@drawable/0</item>
<item>@drawable/1</item>
<item>@drawable/2</item>
<item>@drawable/3</item>
</array>
</resources>
Then in your code:
Resources res = getResources();
TypedArray sprites = res.obtainTypedArray(R.array.icons);
Drawable drawable = sprites.getDrawable(1);
Here's the resources link which gives the background: http://developer.android.com/guide/topics/resources/more-resources.html
来源:https://stackoverflow.com/questions/23176072/android-drawables-is-there-any-way-to-somehow-link-the-int-ids-to-the-r-drawab