Android 根据字符串动态获取资源ID
1.常用方法
public int getResId(String name,Context context){ Resources r = context.getResources(); int id = r.getIdentifier(name,"drawable","com.demo"); return id; }
2.使用反射(推荐,性能高)
public class ResourceMan { public static int getResId(String variableName, Class<?> c) { try { Field idField = c.getDeclaredField(variableName); return idField.getInt(idField); } catch (Exception e) { e.printStackTrace(); return -1; } } }
使用方法:
int id = ResourceMan.getResId("icon",R.drawable.class);
作者:)^程序猿^(
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
喜欢请点击原文右下方"推荐"以示支持,想要了解更多精彩内容,请点击原文"关注我"