[英]Change ImageButton Drawable automatically
I have 320 images in drawable directory and ImageButton so when it's clicked, the Image have to be changed randomly, the image name is like this file_xyz
, the xyz are numbers each one generated randomly using this code:我在drawable目录和 ImageButton 中有 320 个图像,所以当它被点击时,图像必须随机更改,图像名称就像这个
file_xyz
, xyz是每个使用以下代码随机生成的数字:
rand = new Random(System.currentTimeMillis());
x = rand.nextInt(3 - 0) + 0;
y = rand.nextInt(7 - 0) + 0;
z = rand.nextInt(9 - 0) + 0;
return "shape_" + x+ y+ z;
so this gives me a string which I want to use it to change the resource of ImageButton, so how to apply this and make the changes randomly in separate times?所以这给了我一个字符串,我想用它来更改 ImageButton 的资源,那么如何应用它并在不同的时间随机进行更改?
try this:尝试这个:
int resID = getResources().getIdentifier(pDrawableName , "drawable", getPackageName());
imageview.setBackgroundResource(resID);
where String pDrawableName = file_xyz
is your image name其中
String pDrawableName = file_xyz
是您的图像名称
If you first create the exact filename string as in the drawable folder (I'll call it String image), you can do the following:如果您首先在可绘制文件夹中创建确切的文件名字符串(我将其称为字符串图像),您可以执行以下操作:
ImageButton imageButton = (ImageButton) findViewById(R.id.image_button);
imageButton.setImageResource(R.drawable.image);
Where image_button is whatever you have set as the ID for your image button.其中 image_button 是您设置为图像按钮 ID 的任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.