天天看點

android通過反射根據包名和id或name擷取resource ID

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