1. 程式人生 > >android 根據檔名獲取圖片資源id

android 根據檔名獲取圖片資源id

1,

Context context = getBaseContext();
int id = context.getResources().getIdentifier(ImageName, "mipmap", context.getPackageName());

2,

try {
Field field = R.mipmap.class.getDeclaredField(ImageName);
field.setAccessible(true);
int id = field.getInt(field.getName());
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}

3,

try {
Field field = R.mipmap.class.getDeclaredField(ImageName);
field.setAccessible(true);
R.mipmap mipmap = new R.mipmap();
Object oId = field.get(mipmap);
int id =  (Integer) oId;
} catch (Exception e) {
e.printStackTrace();
}