android 通过资源文件名称获取资源文件id

1.
  1. public static Drawable getDrawableByPicName(String picName, Context context) {
  2.         int id = context.getResources().getIdentifier(
  3.                 picName == null ? "no_picture" : picName, "drawable",
  4.                 GlobalConst.PACKAGE_NAME);
  5.         Drawable image = null;
  6.         if (id <= 0) {
  7.             image = context.getResources().getDrawable(R.drawable.no_picture);
  8.         } else {
  9.             image = context.getResources().getDrawable(id);
  10.         }
  11.         return image;
  12.     }
  13. 2.
  14. 可以使用反射,我写了一个小例子。
       
          
          
          
          
    1. public static void main() throws SecurityException, NoSuchFieldException,
    2.             IllegalArgumentException, IllegalAccessException,
    3.             ClassNotFoundException
    4.     {
    5.         String resourceName = "R.drawable.icon";
    6.         String packageName = "com.bbcode";
    7.         int resourceId = getResourceId(packageName, resourceName);
    8.         if(R.drawable.icon == resourceId){
    9.             //success
    10.             ;
    11.         }
    12.     }

    13.     public static int getResourceId(String packageName, String resourceName)
    14.             throws SecurityException, NoSuchFieldException,
    15.             IllegalArgumentException, IllegalAccessException,
    16.             ClassNotFoundException
    17.     {
    18.         String[] splitStr = resourceName.split("\\.");
    19.         String classStr = splitStr[0] + "$" + splitStr[1];
    20.         Class c = Class.forName(packageName + "." + classStr);
    21.         Field f = c.getDeclaredField(splitStr[2]);
    22.         return f.getInt(f.getName());
    23.     }
    24. 3.将图片放到 res/assets 下,不过该方式还没有试过

你可能感兴趣的:(android)