標籤:android 資源擷取
在開發中, 我們習慣了類似下面這種方式去實現引用資源:
context.getResources().getDrawable(R.drawable.flower);
但是,當我們提前知道這個資源的id,想動態去引用,而不是在id裡面固化應該怎麼辦呢? 比如某個圖片資源的id是R.drawable.test_1, 而且有序的還有test_2,test_3, 我們如何動態去引用它們?這裡有兩種方案:直接用反射和用resource的getIdentifier()方法,它們原理都差不多利用反射實現.
第一種方法:
/** * 輸入id,返回Bitmap * @param context * @param id * @return */public static Bitmap getBitMapById(Context context,String id){Bitmap mBitmap=BitmapFactory.decodeResource(context.getResources(),getresourceId("test_"+id));return mBitmap;}public static int getresourceId(String name){ Field field;try {field = R.drawable.class.getField(name);return Integer.parseInt(field.get(null).toString());} catch (NoSuchFieldException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (NumberFormatException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();}return 0; }
第二種方法(更加簡潔):
public static Bitmap getBitmapById(Context context,String id){Resources res = context.getResources();Bitmap mBitmap=BitmapFactory.decodeResource(res, res.getIdentifier(id, "drawable", "com.test.android"));return mBitmap;}
第二種方法中res.getIdentifier()裡面三個參數: 第一個是資源id名,第二個是類名,如果是string類型就是String,還有常見的drawable,layout等等,第三個參數是項目包名.
上面2種方法都能動態擷取資源,當我們知道某些資源的id是規律性的,比如首碼相同,尾碼都是a-z 或者數字排序等等,就能動態構造id擷取資源,而不必每次都寫context.getResources().getDrawable(R.drawable.test_1);
希望對大家有協助.
關於Android中根據ID名動態擷取資源的兩個方法