Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/184.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 更改图像按钮可自动绘制_Android_Random_Android Imagebutton - Fatal编程技术网

Android 更改图像按钮可自动绘制

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+

我在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_按钮是您为图像按钮设置的ID。

我正在尝试,但在编写此代码时,
getResources()
不会仅显示
getClass()
@rafsanahmad007use
getApplicationContext().getResources()
getApplicationContext()相同
@rafsanahmad007u是否在片段中使用它?然后尝试
getActivity().getResources()
…取而代之,您是否检查了生成的图像名称是否与可绘图文件夹中的图像名称完全匹配?