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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM