您的位置:首页 > 移动开发 > Android开发

android 通过资源文件名称获取资源文件id

2013-01-16 12:35 423 查看
1.public static Drawable getDrawableByPicName(String picName, Context context) {

int id = context.getResources().getIdentifier(

picName == null ? "no_picture" : picName, "drawable",

GlobalConst.PACKAGE_NAME);

Drawable image = null;

if (id <= 0) {

image = context.getResources().getDrawable(R.drawable.no_picture);

} else {

image = context.getResources().getDrawable(id);

}

return image;

}
2.
可以使用反射,我写了一个小例子。
public static void main() throws SecurityException, NoSuchFieldException,

IllegalArgumentException, IllegalAccessException,

ClassNotFoundException

{

String resourceName = "R.drawable.icon";

String packageName = "com.bbcode";

int resourceId = getResourceId(packageName, resourceName);

if(R.drawable.icon == resourceId){

//success

;

}

}

public static int getResourceId(String packageName, String resourceName)

throws SecurityException, NoSuchFieldException,

IllegalArgumentException, IllegalAccessException,

ClassNotFoundException

{

String[] splitStr = resourceName.split("\\.");

String classStr = splitStr[0] + "$" + splitStr[1];

Class c = Class.forName(packageName + "." + classStr);

Field f = c.getDeclaredField(splitStr[2]);

return f.getInt(f.getName());

}
3.将图片放到 res/assets 下,不过该方式还没有试过
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: