自动更改 ImageButton Drawable
Change ImageButton Drawable automatically
我在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;
所以这给了我一个字符串,我想用它来更改 ImageButton 的资源,那么如何应用它并在不同的时间随机进行更改?
试试这个:
int resID = getResources().getIdentifier(pDrawableName , "drawable", getPackageName());
imageview.setBackgroundResource(resID);
其中 String pDrawableName = file_xyz
是您的图像名称
如果您首先创建与 drawable 文件夹中完全相同的文件名字符串(我将其称为 String image),您可以执行以下操作:
ImageButton imageButton = (ImageButton) findViewById(R.id.image_button);
imageButton.setImageResource(R.drawable.image);
其中 image_button 是您为图片按钮设置的 ID。
我在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;
所以这给了我一个字符串,我想用它来更改 ImageButton 的资源,那么如何应用它并在不同的时间随机进行更改?
试试这个:
int resID = getResources().getIdentifier(pDrawableName , "drawable", getPackageName());
imageview.setBackgroundResource(resID);
其中 String pDrawableName = file_xyz
是您的图像名称
如果您首先创建与 drawable 文件夹中完全相同的文件名字符串(我将其称为 String image),您可以执行以下操作:
ImageButton imageButton = (ImageButton) findViewById(R.id.image_button);
imageButton.setImageResource(R.drawable.image);
其中 image_button 是您为图片按钮设置的 ID。