Question

I have 718 drawables in the drawable-mdpi, drawable-hdpiand 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?

Was it helpful?

Solution

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

OTHER TIPS

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()); 

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top