android里面,不管是layout,widget,drawable,string,color,array,style等等,android自动会在R.java里面生成resouce ID。那如果只给你包名和widget id 或者string的name,你能得到生成的resouce ID,进而获取这个view或者string吗?实事是可以的。举个栗子给大家看看。
/**
* 得到资源文件.
*
* @param packageName
* 包名
* @param typeName
* 资源类型
* @param instenceName
* 资源名
* @return int
*/
public static int getResourceId(String packageName, String typeName,
String instenceName) {
if (packageName != null && typeName != null && instenceName != null) {
try {
Class> cl = Class.forName(packageName + "$" + typeName);
Field field = cl.getField(instenceName);
Object obj = field.get(cl.newInstance());
return Integer.parseInt(obj.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
return -1;
}
获取string
Toast.makeText(this,getResources().getString(getResourceId("com.figo.study","string","cp_need_agree_protocol")),
Toast.LENGTH_SHORT).show();
获取view
card_number = (TextView) findViewById(getResourceId("com.figo.study", "id", "tv_card_num"));
为什么可以这么做?是因为R.java里面保存了资源的resource id,而且是个内部静态类,通过反射以后就可以获取里面的resouce id了,可以看看R.java是长怎么样的。
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.figo.study;
public final class R {
public static final class anim {
public static final int cpay_push_left_in = 0x7f040000;
public static final int cpay_push_left_out = 0x7f040001;
}
public static final class array {
public static final int cp_auth_idtype = 0x7f050000;
}
public static final class color {
public static final int cp_light_white = 0x7f060000;
public static final int cp_red = 0x7f060001;
}
public static final class dimen {
public static final int dialog_prefered_width = 0x7f070000;
}
public static final class drawable {
public static final int background_dialog = 0x7f020000;
public static final int btn_submit_selector = 0x7f020001;
}
public static final class id {
public static final int tv_card_num = 0x7f0a0038;
public static final int btn_help = 0x7f0a0010;
}
public static final class layout {
public static final int bosh_debitcard_auth = 0x7f030000;
public static final int bosh_dialog_progress = 0x7f030001;
}
public static final class string {
public static final int cp_need_agree_protocol = 0x7f080039;
public static final int cpay_keyboard_letter = 0x7f080033;
}
public static final class style {
public static final int AppBaseTheme = 0x7f090000;
public static final int AppTheme = 0x7f090001;
}
}