如何从唯一键引用可绘制对象
How to reference a drawable from a unique key
在扩充片段时,我需要使用从 activity 传入的唯一字符串键设置一个 ImageView
可绘制对象,但它不是 [=] 的形式18=]。基本上我需要映射一个输入字符串,如:
"earth" --> R.drawable.icon_earth
"mars" --> R.drawable.icon_mars
"pluto" --> R.drawable.icon_pluto
我正在努力寻找在 Android 甚至 Java 中执行此操作的正确方法。也许我只是没有以正确的方式搜索 SO 或 Google,但我已经坚持了一个多小时了。
谢谢。
像这样拍 Map<String, Object>
怎么样 -
Map<String, Object> map = new HasMap<String, Object>();
map.put("earth", R.drawable.icon_earth);
之后,您可以使用 map.get("earth")
从您声明的 Map<String, Object>
- map
中获取值
如果您使用字符串作为图标标识符,您可以使用 getIdentifier method of the Resources class
String resourceName = "icon_" + "earth";
int resource = getResources().getIdentifier(resourceName, "drawable", "com.package");
在扩充片段时,我需要使用从 activity 传入的唯一字符串键设置一个 ImageView
可绘制对象,但它不是 [=] 的形式18=]。基本上我需要映射一个输入字符串,如:
"earth" --> R.drawable.icon_earth
"mars" --> R.drawable.icon_mars
"pluto" --> R.drawable.icon_pluto
我正在努力寻找在 Android 甚至 Java 中执行此操作的正确方法。也许我只是没有以正确的方式搜索 SO 或 Google,但我已经坚持了一个多小时了。
谢谢。
像这样拍 Map<String, Object>
怎么样 -
Map<String, Object> map = new HasMap<String, Object>();
map.put("earth", R.drawable.icon_earth);
之后,您可以使用 map.get("earth")
Map<String, Object>
- map
中获取值
如果您使用字符串作为图标标识符,您可以使用 getIdentifier method of the Resources class
String resourceName = "icon_" + "earth";
int resource = getResources().getIdentifier(resourceName, "drawable", "com.package");