怎么把一个字符串转化为资源的id?

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

你可能感兴趣的:(怎么把一个字符串转化为资源的id?)