[英]how to set a variable imageview src?
I have 52 images of a deck of cards in my Drawable folder, with .png format.我的 Drawable 文件夹中有 52 张纸牌图像,格式为 .png。
I want to modify my andorid:src attribute of an ImageView, but using a var wich saves the name of my image name.我想修改 ImageView 的 andorid:src 属性,但使用 var 可以保存我的图像名称。 For example.
例如。
String nameOfCard="two_of_diamonds"; // and as I said I have an Image called two_of_diamonds in my Drawable folder
I tried several ways but I didn´t find the correct one.我尝试了几种方法,但没有找到正确的方法。 If I use: imageview.setImageResource(int) I need an int not a String reference.
如果我使用: imageview.setImageResource(int) 我需要一个 int 而不是 String 引用。
any Idea?任何的想法? Thanks !
谢谢 !
Use the following code to access drawable resources using name: 使用以下代码使用名称访问可绘制资源:
Resources resources = getResources();
final int resourceId = resources.getIdentifier("two_of_diamonds",
"drawable", getPackageName());
imgView.setImageResource(resourceId);
Use getIdentifier()
使用
getIdentifier()
public int getIdentifier (String name, String defType, String defPackage)
public int getIdentifier(字符串名称,字符串defType,字符串defPackage)
This will return the id. 这将返回ID。 Use the id to set image resource for
imageview
. 使用id设置
imageview
图像资源。
For example, 例如,
int id = getResources().getIdentifier(nameOfCard,"drawable",getPackageName());
imageview.setImageResource(id);
Create an Object of Image like 创建一个像图像的对象
class Image{
String Name;
int Id;
public Image(String Name,int id){
this.Name=Name;
Id=id;
}
}
Create an Array of Images 创建图像阵列
Image[] images = {new Image("name",R.drawable.name_of_image),...);
When Setting image use 设定图像使用时
for(Image i: images){
if(i.Name.equals("desired")){
imageview.setImageDrawable(i.Id);
}
}
There must be a better approach to the problem than this. 解决这个问题必须有比这更好的方法。 It is a very basic one.
这是非常基本的。
I needed this in Kotlin and used Deven's answer.我在 Kotlin 中需要这个并使用了 Deven 的答案。 It became:
它变成了:
// 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.