gpt4 book ai didi

java - Android 从数组中随机动态改变背景

转载 作者:行者123 更新时间:2023-12-01 10:32:57 24 4
gpt4 key购买 nike

我是 Android 新手,我正在尝试更改 Java 中 ImageView 的背景。这部分正在发挥作用。问题是我有 4 张图像,我想随机选择一张并显示该图像。

例如,我有一个可绘制数组:

String[] images = new String[4];
images[0] = "R.drawable.i1";
images[1] = "R.drawable.i2";
images[2] = "R.drawable.i3";
images[3] = "R.drawable.i4";

我试图用它来选择一个随机的:

int idx = new Random().nextInt(images.length);
String random = (images[idx]);

但是,我似乎无法让 imageview 的 setBackground 与这些一起使用。

例如,我尝试过:

images.setBackgroundDrawable( getResources().getDrawable(R.drawable.images[random]) );

我知道我做得不对,但这就是我想做的。

最佳答案

你可以试试这个:

    int[] images = new int[4];
images[0] = R.drawable.i1;
images[1] = R.drawable.i2;
images[2] = R.drawable.i3;
images[3] = R.drawable.i4;

int idx = new Random().nextInt(images.length);
int random = (images[idx]);
images.setBackgroundDrawable( getResources().getDrawable(images[random]) );

关于java - Android 从数组中随机动态改变背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34993491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com