[英]how to set a variable imageview src?
我的 Drawable 文件夾中有 52 張紙牌圖像,格式為 .png。
我想修改 ImageView 的 andorid:src 屬性,但使用 var 可以保存我的圖像名稱。 例如。
String nameOfCard="two_of_diamonds"; // and as I said I have an Image called two_of_diamonds in my Drawable folder
我嘗試了幾種方法,但沒有找到正確的方法。 如果我使用: imageview.setImageResource(int) 我需要一個 int 而不是 String 引用。
任何的想法? 謝謝 !
使用以下代碼使用名稱訪問可繪制資源:
Resources resources = getResources();
final int resourceId = resources.getIdentifier("two_of_diamonds",
"drawable", getPackageName());
imgView.setImageResource(resourceId);
使用getIdentifier()
public int getIdentifier(字符串名稱,字符串defType,字符串defPackage)
這將返回ID。 使用id設置imageview
圖像資源。
例如,
int id = getResources().getIdentifier(nameOfCard,"drawable",getPackageName());
imageview.setImageResource(id);
創建一個像圖像的對象
class Image{
String Name;
int Id;
public Image(String Name,int id){
this.Name=Name;
Id=id;
}
}
創建圖像陣列
Image[] images = {new Image("name",R.drawable.name_of_image),...);
設定圖像使用時
for(Image i: images){
if(i.Name.equals("desired")){
imageview.setImageDrawable(i.Id);
}
}
解決這個問題必須有比這更好的方法。 這是非常基本的。
我在 Kotlin 中需要這個並使用了 Deven 的答案。 它變成了:
// THIS IS KOTLIN, NOT JAVA
var diceRoll = dice.roll()
var diceRoll2 = dice.roll()
// Update the screen with the dice roll
diceImage.setImageResource(getMyResource("dice_" + diceRoll))
diceImage2.setImageResource(getMyResource("dice_" + diceRoll2))
fun getMyResource(imageName: String):Int{
val resources: Resources = resources
val resourceId: Int = resources.getIdentifier(
imageName,
"drawable", this.packageName
)
return resourceId
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.