在写android时,我们经常使用资源文件的id来代替这个资源,如 R.drawable.* ,
那怎样通过文件名得到这个资源的Id的,请看过来
- 第一
`public int getResId(String name,Context context){
Resources r = context.getResources();
int id = r.getIdentifier(name,"drawable",context.getPackageName());
return id;
}`
- 第二
` 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;
}
}`
使用方式
getResId(“loading”+tag,R.drawable.class);
int tag=new Random().nextInt(4);
int pl= MyApplication.getResId("loading"+tag,R.drawable.class);
if(pl==1)
pl=R.drawable.loading1;