Android drawables : Is there any way to somehow link the int IDs to the R drawable IDs?

僤鯓⒐⒋嵵緔 提交于 2019-12-12 04:13:07

问题


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?


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!