How to get list of image with R.Drawable

风格不统一 提交于 2019-12-24 18:27:26

问题


In order to create a tile management system I have a pack of image in my res/drawable directory. How to load that ressource dynamically ?

like : F_16.0_0_112.jpg. ("F_"+zoom"+"._"+XCoord+"_"+YCoord".jpg")

Is there a fonction like getDrawable(String) ?


回答1:


You can get a drawable using its name by:

int id = getResources().getIdentifier("name_of_resource", "id", getPackageName());



回答2:


You can get this using reflection (dont forget to import java.lang.reflect.Field)

/**
 * For example calling <code>getDrawableId("ic_launcher")</code> will return the same value as <code>R.drawable.ic_launcher;</code> 
 * 
 * @param name the name of the field
 * @return the drawable id
 */
public int getDrawableId(String name) {
    Class<?> c = R.drawable.class;
    Field f = null;
    int id = 0;

    try {
        f = R.drawable.class.getField(name);
        id = f.getInt(null);
    } catch (NoSuchFieldException e) {
        Log.i("Reflection", "Missing drawable " + name);
    } catch (IllegalAccessException e) {
        Log.i("Reflection", "Illegal access to field " + name);
    }

    return id;
}



回答3:


No, for this use android assets folder.

Please see more details here.




回答4:


Unfortunatly no, you can't load resources by name. The id's are variables in the generated R class. In java, you can't build dynamic variable names.



来源:https://stackoverflow.com/questions/13266774/how-to-get-list-of-image-with-r-drawable

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