public static int getResourdIdByResourdName(Context context, String
ResName){
int resourceId = 0;
try {
Field field = R.drawable.class.getField(ResName);
field.setAccessible(true);
try {
resourceId = field.getInt(null);
} catch (IllegalArgumentException e) {
log.showLogDebug("IllegalArgumentException:" + e.toString());
} catch (IllegalAccessException e) {
log.showLogDebug("IllegalAccessException:" + e.toString());
}
} catch (NoSuchFieldException e) {
log.showLogDebug("NoSuchFieldException:" + e.toString());
}
return resourceId;
}
调用:
int resId = CommonUtil.getResourdIdByResourdName(mContext, "btn_new");
int resourceId = 0;
try {
Field field = R.drawable.class.getField(ResName);
field.setAccessible(true);
try {
resourceId = field.getInt(null);
} catch (IllegalArgumentException e) {
log.showLogDebug("IllegalArgumentException:" + e.toString());
} catch (IllegalAccessException e) {
log.showLogDebug("IllegalAccessException:" + e.toString());
}
} catch (NoSuchFieldException e) {
log.showLogDebug("NoSuchFieldException:" + e.toString());
}
return resourceId;
}
调用:
int resId = CommonUtil.getResourdIdByResourdName(mContext, "btn_new");
本文介绍了一种通过资源名称获取资源ID的方法,并提供了具体的实现代码。该方法使用反射机制从资源包中查找对应的资源ID,适用于Android开发场景。
2778

被折叠的 条评论
为什么被折叠?



