2013-04-30 64 views
1

我正在嘗試創建一個例程,它將一張卡片圖像分配給ImageView,而不使用如下所示的內容:R.drawable.card_10clover。我寧願使用一個字符串,但我這樣做的方式不起作用。如何在Android中使用字符串將圖像資源分配給ImageView

String imgRes = "R.drawable.card_"; 
int num = 10; 
imgRes += "10"; 
String suit = "clover"; 
imgRes += "suit; 
ImageView card = (ImageView) findViewById(R.id.imgcard); 
card.setImageResource(imgRes); 

不幸的是setImageResource只接受一個int。請幫忙。

謝謝您,傑克 藍

回答

0

使用則getIdentifier(字符串名稱,字符串DEFTYPE,字符串defPackage); Your imgRes不需要前綴R.可提取

String imgRes = "card_"; 
int num = 10; 
imgRes += "10"; 
String suit = "clover"; 
imgRes += "suit; 
ImageView card = (ImageView) findViewById(R.id.imgcard); 
int resourceId = getResource().getIdentifier (imgRes, "drawable", "com...."); 
card.setImageResource(resourceId); 
+0

非常感謝。這真的很好。爲了使上面的代碼工作,我需要做到這一點:getResources()。getIdentifier(....);我想創建一個不同的類(擴展對象),所以我只傳遞了getResources返回的資源。再次感謝。 – 2013-04-30 03:13:51

相關問題