Android之使用getIdentifier()获取资源Id
生活随笔
收集整理的這篇文章主要介紹了
Android之使用getIdentifier()获取资源Id
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
使用getIdentifier()方法可以方便的獲各應(yīng)用包下的指定資源ID。
主要有兩種方法:
(1)方式一
Resources resources = context.getResources();
int indentify = resources. getIdentifier( org.loveandroid.androidtest:drawable/icon", null, null);
if(indentify>0){
icon = resources.getDrawable(indentify);
}
第一個參數(shù)格式是:包名 + : +資源文件夾名 + / +資源名;是這種格式?然后其他的可以為null?
(2)方式二
Resources resources = context.getResources();
intindentify =?getResources().getIdentifier("icon",?"drawable",?"org.anddev.android.testproject");
第一個參數(shù)為ID名,第二個為資源屬性是ID或者是Drawable,第三個為包名。?
如果找到了,返回資源Id,如果找不到,返回0 。
從數(shù)據(jù)庫里讀取圖片名稱,然后調(diào)用圖片。直接用R.drawable.?無法調(diào)用。查了好多地方最后找到了個方法,分享給大家,希望有幫助。
主要由兩種方法,個人建議第二種。
1.不把圖片放在res/drawable下,而是存放在src某個package中(如:com.drawable.resource),這種情況下的調(diào)用方法為:
String path = "com/drawable/resource/imageName.png"; InputStream is = getClassLoader().getResourceAsStream(path); Drawable.createFromStream(is, "src");
2. 如果還是希望直接使用res/drawable中的圖片,就需要通過下面的方法了:
假設(shè)創(chuàng)建工程的時候,填寫的package名字為:com.test.image
int resID = getResources().getIdentifier("imageName", "drawable","com.test.image");
Drawable image = getResources().getDrawable(resID);
主要有兩種方法:
(1)方式一
Resources resources = context.getResources();
int indentify = resources. getIdentifier( org.loveandroid.androidtest:drawable/icon", null, null);
if(indentify>0){
icon = resources.getDrawable(indentify);
}
(2)方式二
Resources resources = context.getResources();
intindentify =?getResources().getIdentifier("icon",?"drawable",?"org.anddev.android.testproject");
如果找到了,返回資源Id,如果找不到,返回0 。
寫了一個方法:獲取資源ID,如果不存在返回0
static int getResourceId(Context context,String name,Stringtype,String packageName){ResourcesthemeResources=null;PackageManager pm=context.getPackageManager();try {themeResources=pm.getResourcesForApplication(packageName);returnthemeResources.getIdentifier(name, type, packageName);} catch(NameNotFoundException e) {e.printStackTrace();}return0;}從數(shù)據(jù)庫里讀取圖片名稱,然后調(diào)用圖片。直接用R.drawable.?無法調(diào)用。查了好多地方最后找到了個方法,分享給大家,希望有幫助。
主要由兩種方法,個人建議第二種。
1.不把圖片放在res/drawable下,而是存放在src某個package中(如:com.drawable.resource),這種情況下的調(diào)用方法為:
String path = "com/drawable/resource/imageName.png"; InputStream is = getClassLoader().getResourceAsStream(path); Drawable.createFromStream(is, "src");
2. 如果還是希望直接使用res/drawable中的圖片,就需要通過下面的方法了:
假設(shè)創(chuàng)建工程的時候,填寫的package名字為:com.test.image
int resID = getResources().getIdentifier("imageName", "drawable","com.test.image");
Drawable image = getResources().getDrawable(resID);
總結(jié)
以上是生活随笔為你收集整理的Android之使用getIdentifier()获取资源Id的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android之状态栏通知Notific
- 下一篇: Android之 如何在退出一个acti