本文實(shí)例講述了Android使用getIdentifier()獲取資源Id的方法。分享給大家供大家參考,具體如下:
int i= getResources().getIdentifier("icon", "drawable", getPackageName()) ;if(i>0) {Log.i("aa","aa");}else {Log.i("vbv","aa");}或者:
int resID = getResources().getIdentifier("org.loveandroid.androidtest:drawable/gallery_photo_1",null,null);int resID = getResources().getIdentifier("org.anddev.android.testproject:drawable/bug", null, null);// orint resID = getResources().getIdentifier("bug", "drawable", "org.anddev.android.testproject");//第一個(gè)參數(shù):full_package:type/filename_without_ending是這種格式 然后其他的可以為nullint idFlag = getResources().getIdentifier(getPackageName() + ":drawable/flag", null, null);// 或是int idFlag = getResources().getIdentifier("flag", "drawable", getPackageName());var Drawable[] dw = new Drawable[10];for (int i = 1; i <= 10; i++) { int id = getResources().getIdentifier("flag" + i, "drawable", getPackageName()); dw[i-1] = getResources().getDrawable(id);}//用反射法 可以得到 所有的資源private void _DumpAllResourceIDs(Class<?> classType) throws IllegalArgumentException { Field[] fIDs = classType.getFields(); try { for (int i = 0; i < fIDs.length; i++) { Field fld = fIDs[i]; int nID = fld.getInt(null); Log.d("dbg", classType.getSimpleName() + " " + i + ": " + fld.getName() + "=" + nID); } } catch (Exception e) { throw new IllegalArgumentException(); }}import java.lang.reflect.Field;... _DumpAllResourceIDs(R.layout.class); _DumpAllResourceIDs(R.drawable.class);結(jié)果:
R$layout 0: main=2130903040
R$layout 1: small_spinner_dropdown_item=2130903041
R$drawable 0: icon=2130837504
有時(shí)候我們需要?jiǎng)討B(tài)的取得一個(gè)一個(gè)控件的id,然后進(jìn)行操作,經(jīng)過在網(wǎng)上查找,找到了一下方法
getResources().getIdentifier("textView01", "id", "cn.xxx.xxx");第一個(gè)參數(shù)為ID名,第二個(gè)為資源屬性是ID或者是Drawable,第三個(gè)為包名。
做項(xiàng)目過程中遇到一個(gè)問題,從數(shù)據(jù)庫(kù)里讀取圖片名稱,然后調(diào)用圖片。直接用R.drawable.?無法調(diào)用。查了好多地方最后找到了個(gè)方法,分享給大家,希望有幫助。
主要由兩種方法,個(gè)人建議第二種。
1. 不把圖片放在res/drawable下,而是存放在src某個(gè)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)建工程的時(shí)候,填寫的package名字為:com.test.image
int resID = getResources().getIdentifier("imageName", "drawable", "com.test.image");Drawable image = getResources().getDrawable(resID);更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android視圖View技巧總結(jié)》、《Android編程之a(chǎn)ctivity操作技巧總結(jié)》、《Android操作SQLite數(shù)據(jù)庫(kù)技巧總結(jié)》、《Android操作json格式數(shù)據(jù)技巧總結(jié)》、《Android數(shù)據(jù)庫(kù)操作技巧總結(jié)》、《Android文件操作技巧匯總》、《Android編程開發(fā)之SD卡操作方法匯總》、《Android開發(fā)入門與進(jìn)階教程》、《Android資源操作技巧匯總》及《Android控件用法總結(jié)》
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選