[英]Android change background dynamically randomly from array
I am new to Android and I am trying to change the background of an ImageView in Java. 我是Android的新手,正在尝试更改Java中ImageView的背景。 This part is working. 这部分正在工作。 The problem is I have a 4 images and I would like to randomly choose one and display the image. 问题是我有4张图像,我想随机选择一张并显示图像。
For example I have an array of drawables as such: 例如我有这样的可绘制数组:
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";
I was trying to use this to choose a random one: 我试图用它来选择一个随机的:
int idx = new Random().nextInt(images.length);
String random = (images[idx]);
However, I cannot seem to get the setBackground for the imageview to work with these. 但是,我似乎无法获得setBackground来使imageview与它们一起使用。
For example, I tried: 例如,我尝试过:
images.setBackgroundDrawable( getResources().getDrawable(R.drawable.images[random]) );
I know I am not doing it correctly however that is what I would like to do. 我知道我做的不正确,但是那是我想做的。
You can try this: 您可以尝试以下方法:
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]) );
Your problem seems to be, that you want to call a Method through a String. 您的问题似乎是,您想通过字符串调用方法。 Thats absolutly nonesense unless you work with java SQL calls or XML...whatever. 除非您使用java SQL调用或XML,否则绝对没有任何意义。 you need the actual image Object if you call your draw method. 如果调用draw方法,则需要实际的图像Object。
well there is a simple solution :D Instead of using an String[]
. 好了,有一个简单的解决方法:D而不是使用String[]
。 Use a ArrayList<Image>
after that you can call the method list.shuffle()
. 之后,可以使用ArrayList<Image>
调用方法list.shuffle()
。
some pseudo Code: 一些伪代码:
ArrayList<Image> yourImages = new Arraylist<>();
yourImages[1] = image1
yourImages[2] = image2
...
yourImages.shuffle(); //shuffles your list
print(yourImages[1]);
print(yourImages[2]);
...
the first advatage is that your pictures will be displayed at random. 第一个优点是您的图片将随机显示。 the second advantage is that there is no duplicate of each displayed picture. 第二个优点是每个显示的图片没有重复。
PS: It would also work with an Image[] + the Random class. PS:它也可以与Image [] + Random类一起使用。 But how come, choose a String[]. 但是,为什么要选择String []。 a String is a representation of an Text... not an image. 字符串表示文本,而不是图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.