android 由资源名称获得ID的方法

我的思路是,在string.xml文件里头建一个String-array,用来配置资源的名称,例如图片,使得外部的资源改变时,通过xml的配置免得去修改源程序:

 

	<string-array name="tab_icons">
		<item>g_more_detail</item>
		<item>g_reset_pw</item>
		<item>g_personal_info</item>
		<item>g_exit</item>
	</string-array>

 在某处引用该字符串数组:

Resources res = context.getResources();
String[] tab1 = res.getStringArray(R.array.tab_icons);

 以下方法为资源名称与资源ID的对换:

private ArrayList<Integer> names2Ids(String[] ss, Resources res){
	ArrayList<Integer> list = null;
	if(ss.length>0){
		list = new ArrayList<Integer>();
		for(int i=0; i<ss.length; i++){
			int id = res.getIdentifier(
                                                                  ss[i],   //资源名称的字符串数组
                                                                  "drawable", //资源类型
                                                                  "com.test");  //R类所在的包名
			list.add(id);
		}
	}
	return list;
}

  调用该方法:

Resources res = context.getResources();
private ArrayList<Integer> drawables01 = names2Ids(tab1, res);

 

使用以上方法,在一定的程度上提高了程序的可维护性,但是通过res.getIdentifier()方法来获得资源的ID,在去应用资源,其运行的效率,可真要掂量掂量,引用API上的注释:此方法不推荐使用,引用资源最好使用其全局的ID!

 

另外,通过ID获取资源名称的方法也十分简单:getResourceName(int resid)

你可能感兴趣的:(android,xml)