---
title: "android 通过字符串来获得id"
author: "vocaloid"
date: "2012-10-06T19:25:43Z"
tags: []
categories: ["移动开发"]
slug: "android-id"
draft: false
lastmod: "2012-10-06T19:28:58Z"
id: 1691944
url: "https://vocaloid.iteye.com/blog/1691944"
---

第一种方法：

 

 

```
try{
		Field field=R.drawable.class.getField("icon");   
		int i= field.getInt(new R.drawable());   
	  	Log.d("icon",i+"");
	}catch(Exception e){   
		Log.e("icon",e.toString());   
	}
```

 

   似乎是用反射的方式来取id，这种我不经常用....

 

 

第二种方法：

 

```
	Resources res=getResources();   
	int i=res.getIdentifier("icon","drawable",getPackageName());   
	  
	Log.i("res",Integer.toString(i));
```

 

 

第二个参数是设置要获取id对象的类型，如若是view对象，则使用"id"便可比如

 

 

```
Res.getIdentifier(“[viewname]”,”id”, getPackageName());
```

 

这样的话就可以使用循环来获取drawable中的有序命名的图片资源，而不必一个个写出来了。