每次单击将图像随机设置为ImageButton

问题描述 投票:-2回答:2

我正在尝试从图像制作按钮,其想法是每次单击按钮都会更改图像,因此按钮的形状和外观也会改变。

例如,每次点击都会给出一个点,并且每个形状或基于我为此目的制定的算法选择“图像”

,我有这三个变量,其值在此代码中是随机生成的:

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 button random imagebutton
2个回答
3
投票

您可以通过使用下面的代码来做到这一点:

int resource = getResources().getIdentifier(myID, "drawable", "com.your.package");

PS:从名称中删除“ R.id.”。


0
投票
  1. 重命名您的图像,例如image1,image2,...,image150。

  2. 生成一个介于1到150之间(包括两端)的随机数。

  3. 使用以下代码获取图像资源ID。 (如果已将图像放置在mipmap文件夹中,请使用“ mipmap”而不是“ drawable”)

    String myID = "image"+ generatedRandomNumber;
    int resource = getResources().getIdentifier(myID, "drawable", "com.your.package");
    
  4. 使用此资源ID设置ImageButton的图像。

© www.soinside.com 2019 - 2024. All rights reserved.