關於Android中根據ID名動態擷取資源的兩個方法

來源:互聯網
上載者:User

標籤: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名動態擷取資源的兩個方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.