在android中,我們經常使用資源檔的id來代替這個資源,如 R.drawable.*** ,
那怎樣通過檔案名稱得到這個資源的Id的,這裡介紹兩種方法:
一:通過 getIdentifier (String name, String defType, String defPackage)方法。
這裡有兩種實現
1.name 用package:type/entry,那麼後面兩個參數可以為null.
2.name唯寫檔案名稱,後面兩參數分別為檔案類型和包路徑。
二:通過反射機制:
給個demo: drawable檔案夾中有一bluetooth.png圖片。
package com.shao.acts;</p><p>import java.lang.reflect.Field;</p><p>import android.app.Activity;<br />import android.os.Bundle;</p><p>public class GetResIdActivity extends Activity {<br /> /** Called when the activity is first created. */<br /> @Override<br /> public void onCreate(Bundle savedInstanceState) {<br /> super.onCreate(savedInstanceState);<br /> setContentView(R.layout.main);</p><p> //方式一:<br /> int resId1 = getResources().getIdentifier("bluetooth", "drawable", "com.shao.acts");<br /> if(R.drawable.bluetooth==resId1){<br /> System.out.println("TRUE");<br /> }<br /> //方式二:<br /> int resId2 = getResources().getIdentifier("com.shao.acts:drawable/bluetooth", null, null);<br /> if(R.drawable.bluetooth==resId2){<br /> System.out.println("TRUE");<br /> }<br /> //方式三:<br /> int resId3 = getImage("bluetooth");<br /> if(R.drawable.bluetooth==resId3){<br /> System.out.println("TRUE");<br /> }<br /> }<br /> public static int getImage(String pic) {<br /> if(pic==null||pic.trim().equals("")){<br /> return R.drawable.icon;<br /> }<br /> Class draw = R.drawable.class;<br /> try {<br /> Field field = draw.getDeclaredField(pic);<br /> return field.getInt(pic);<br /> } catch (SecurityException e) {<br /> return R.drawable.icon;<br /> } catch (NoSuchFieldException e) {<br /> return R.drawable.icon;<br /> } catch (IllegalArgumentException e) {<br /> return R.drawable.icon;<br /> } catch (IllegalAccessException e) {<br /> return R.drawable.icon;<br /> }<br /> }<br />}
輸出都為true.不信可以試試,O(∩_∩)O~