1 android
我需要一个使用setImageResource方法设置随机图像的帮助.在drawable文件夹中,我有一个名为photo0.jpg的jpeg文件,photo1.jpg ... photo99.jpg.以下代码有效:
int p = R.drawable.photo1;
image.setImageResource(p);
Run Code Online (Sandbox Code Playgroud)
以上将显示photo1.jpg但我想显示一个随机图像.我尝试了以下但它不起作用.
String a = "R.drawable.photo";
int n = (int) (Math.random()*100)
String b = Integer.toString(n);
String c = a+b;
int p = Integer.parseInt(c);//checkpoint
image.setImageResource(p);
Run Code Online (Sandbox Code Playgroud)
似乎字符串"R.drawable.photoXX"在检查点未被更改为整数.有人可以教我一个正确的代码吗?先感谢您.
小智 5
Strings are pretty much evil when it comes to work like this due to the overhead costs. Since Android already provides you with integer id's I would recommend storing all of them to an int array and then using a random number for the index.
The code would look something like this:
int imageArr[] = new int[NUM_IMAGES];
imageArr[1] = R.drawable.photo;
//(load your array here with the resource ids)
int n = (int)Math.random()*NUM_IMAGES;
image.setImage(imageArr[n]);
Run Code Online (Sandbox Code Playgroud)
在这里,我们有一个非常直接的实现,并绕过字符串concats发生的所有创建和破坏.
| 归档时间: |
|
| 查看次数: |
9898 次 |
| 最近记录: |