2012-11-12 42 views
26

可能重複:所有對不起的稱號
Android - Open resource from @drawable String查找繪製的字符串

第一,但我不知道到底是什麼頭銜,我可以設置。

好吧,這裏是我的問題:

我會從外部數據庫recibe的字符串,例如:「picture0001」。

在res/drawable文件夾中我有一張圖片,其名稱是picture0001。

我想將該圖片設置爲ImageView的背景(源)。

問題是,我如何使用從外部數據庫獲得的字符串來查找此圖片。

非常感謝。

回答

113

是的,您可以使用Resources.getIdentifier()按名稱查找它。

Context context = imageView.getContext(); 
int id = context.getResources().getIdentifier("picture0001", "drawable", context.getPackageName()); 
imageView.setImageResource(id); 

它效率不高,但它可以查找偶爾的資源。

+0

@QuinDa Great !不要忘記點擊答案旁邊的複選標記,如果它適合你 - 它會幫助你在將來得到更好的答案! ;) – Eric

+0

我試過了,但它說:Vote Up需要15點聲望): – QuinDa

+0

@QuinDa複選標記,而不是向上箭頭(對,需要15點聲望)。但它似乎已經發現它! :) – Eric

4

您也可以使用反射像這樣:

Class c = Class.forName("your.project.package.R"); 
Field f = c.getDeclaredField("drawable"); 
Class d = f.getDeclaringClass(); 
Field f2 = d.getDeclaredField("yourstring"); 
int resId = f2.getInt(null); 
Drawable d = getResources().getDrawable(resId); 

雖然,最好的解決辦法是什麼MarvinLabs建議。

+3

我覺得'Resources.getIdentifier'可能比這個更容易。 – Tim

+0

太棒了!我不知道這種方法。謝謝! –

+0

是的,但是這個解決方案速度更快(超過40%) –