Android 更改图像按钮可自动绘制
我在drawable目录和ImageButton中有320个图像,因此当单击时,图像必须随机更改,图像名称如下Android 更改图像按钮可自动绘制,android,random,android-imagebutton,Android,Random,Android Imagebutton,我在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+
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_按钮是您为图像按钮设置的ID。我正在尝试,但在编写此代码时,
getResources()
不会仅显示getClass()
@rafsanahmad007usegetApplicationContext().getResources()
与getApplicationContext()相同
@rafsanahmad007u是否在片段中使用它?然后尝试getActivity().getResources()
…取而代之,您是否检查了生成的图像名称是否与可绘图文件夹中的图像名称完全匹配?