背景在某些應用中,為了實現應用apk資源放入重復利用,或者使用反射得到本應用的資源,需要使用反射方式獲得,但Resources類中也自帶了這種獲取方式,并且功能更加強大你可以獲取string,color,drawable,raw,xml等文件,因此也就意味著,這里可以獲取的資源是res中已定義的資源,對于控件id的獲取,暫時無法做到public int getIdentifier(String name, String defType, String defPackage) {if (name == null) {throw new NullPointerException("name is null");}try {return Integer.parseInt(name);} catch (Exception e) {// Ignore }return mAssets.getResourceIdentifier(name, defType, defPackage); }獲取資源的Id獲取當前應用的資源Idint drawableId = mContext.getResources().getIdentifier("ic_launcher","drawable", mContext.getPackageName()); mImageView.setImageResource(drawableId);獲取其他應用的資源Idint id = mContext.getResources().getIdentifier("icon", "drawable", "com.android.testproject"); // 或者 int id = mContext.getResources().getIdentifier("com.android.testproject:drawable/icon", null, null);整合到一起public static int getResourceId(Context context, String name, String type, String packageName){Resources themeResources=null;PackageManager pm=context.getPackageManager();try {themeResources=pm.getResourcesForApplication(packageName);return themeResources.getIdentifier(name, type, packageName);} catch (NameNotFoundException e) {e.printStackTrace();}return 0; }獲取系統資源Idint id = getResources().getIdentifier("actionbar_bg", "drawable","android"); //注意,最后一個參數必須是“android” 獲取資源的Uriandroid系統中,應用的資源存儲時也通常會被存入 數據庫,也可以被共享, 因此來說資源也可以獲得uripublic static Uri getResourceUri(int resId,String packageName) {return Uri.parse("android.resource://"+packageName+"/"+resId); }
?