主要有兩種方法:
(1)方式一
Resources resources = context.getResources();
int indentify = resources.getIdentifier(org.loveandroid.androidtest:drawable/icon",null,null);
if(indentify>0){
icon = resources.getDrawable(indentify);
}
-
第一個參數格式是:包名 + : + 資源文件夾名
+ / +資源名;是這種格式 然後其他的可以爲null
(2)方式二
Resources resources = context.getResources();
int indentify= getResources().getIdentifier("icon", "drawable", "org.anddev.android.testproject");
-
第一個參數爲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);