android 使用getIdentifier()獲取資源Id

使用getIdentifier()方法可以方便的獲各應用包下的指定資源ID。
主要有兩種方法:
(1)方式一
Resources resources = context.getResources();
int indentify = resources.getIdentifier(org.loveandroid.androidtest:drawable/icon",null,null);
if(indentify>0){
icon = resources.getDrawable(indentify);
}
  1. 第一個參數格式是:包名 + : + 資源文件夾名 + / +資源名;是這種格式 然後其他的可以爲null 

(2)方式二
Resources resources = context.getResources();
int indentify= getResources().getIdentifier("icon""drawable""org.anddev.android.testproject");
  1. 第一個參數爲ID名,第二個爲資源屬性是ID或者是Drawable,第三個爲包名。  

如果找到了,返回資源Id,如果找不到,返回0 。

寫了一個方法:獲取資源ID,如果不存在返回0
static int getResourceId(Context context,String name,String type,String packageName){
        Resources themeResources=null;
        PackageManager pm=context.getPackageManager();
        try {
            themeResources=pm.getResourcesForApplication(packageName);
            return themeResources.getIdentifier(name, type, packageName);
        } catch (NameNotFoundException e) {

            e.printStackTrace();
        }
        return 0;
 }

從數據庫裏讀取圖片名稱,然後調用圖片。直接用R.drawable.?無法調用。查了好多地方最後找到了個方法,分享給大家,希望有幫助。
主要由兩種方法,個人建議第二種。
1. 不把圖片放在res/drawable下,而是存放在src某個package中(如:com.drawable.resource),這種情況下的調用方法爲:
String path = "com/drawable/resource/imageName.png";
InputStream is = getClassLoader().getResourceAsStream(path);
Drawable.createFromStream(is, "src");

2. 如果還是希望直接使用res/drawable中的圖片,就需要通過下面的方法了:
假設創建工程的時候,填寫的package名字爲:com.test.image
int resID = getResources().getIdentifier("imageName", "drawable", "com.test.image");
Drawable image = getResources().getDrawable(resID);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章