Android,從字符串中獲取資源ID?我需要將一個資源ID傳遞給我的一個類中的一個方法。它需要同時使用引用指向的id和字符串。我應該如何才能最好地做到這一點呢?例如:R.drawable.icon我需要獲得它的整數ID,但我也需要訪問字符串“圖標”。如果我要傳遞給這個方法的是“圖標”字符串,那就更好了。
3 回答

慕無忌1623718
TA貢獻1744條經驗 獲得超4個贊
Resources.getIdentifier()
public static int getResId(String resName, Class<?> c) { try { Field idField = c.getDeclaredField(resName); return idField.getInt(idField); } catch (Exception e) { e.printStackTrace(); return -1; } }
R.drawable.icon
int resID = getResId("icon", R.drawable.class); // or other resource class
Resources.getIdentifier()
- 3 回答
- 0 關注
- 766 瀏覽
添加回答
舉報
0/150
提交
取消