天天看點

Android根據圖檔檔案名擷取它的資源ID 的兩種方式

     假如在drawable目錄下放一個圖檔檔案,由于一些原因,我們在程式中僅僅知道它的檔案名,而不知道它的資源ID,當我們需要這個資源ID的時候,可以使用下面的一行代碼擷取到:

方法一:

1. /**
2.    * 擷取圖檔名稱擷取圖檔的資源id的方法
3.    * @param imageName
4.    * @return
5.    */
6. public int
7. Context ctx=getBaseContext();  
8. int resId = getResources().getIdentifier(imageName, "drawable"
9. return      

 方法二:

1. /**
2.  * 擷取圖檔名稱擷取圖檔的資源id的方法
3.  * @param imageName
4.  * @return
5.  */
6. public int
7. class;  
8. null;  
9. int
10. try
11.            field = drawable.getField(imageName);  
12.            r_id = field.getInt(field.getName());  
13. catch
14.         r_id=R.drawable.b_nothing;  
15. "ERROR", "PICTURE NOT FOUND!");  
16.        }  
17. return
18. }      

​​知道資源ID,擷取資源的檔案名​​

  1. getResources().getResourceName(resid)