我正在尝试从图像制作一个按钮,其想法是每次单击按钮都会更改图像,因此按钮的形状和外观也会发生变化。
E.g., every click gives a point, and every shape or "image" is selected based on an algorithm I made for this purpose
我有这三个变量,其值在下面的代码中随机生成:
rand = new Random(System.currentTimeMillis());
x = rand.nextInt(3);
y = rand.nextInt(8);
z = rand.nextInt(10);
将生成的数字分配给字符串,以使用以下代码创建图像的下一个 id
:
String myID = "R.id.myImage_" + x + y + z;
我使用这个代码:
int resource = getResources().getIdentifier(myID, "drawable", "com.asgames.package");
但是,我仍然收到找不到图像的错误。
最佳答案
要在 Android 中为 View
生成随机 ID,您可以使用 generateViewId()
,它是 View
类中的一个方法 bundle 在 Android 库中,文档说:
Generate a value suitable for use in setId(int). This value will not collide with ID values generated at build time by aapt for R.id.
查看官方文档here .
现在您可以执行以下操作:
int imageCoordinates = x + y + z;
int imageId = View.generateViewId() + imageCoordinates;
关于android - 每次点击时随机将 Image 设置为 ImageButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42322151/