我的原始文件夹中有一堆图像,名称范围从 1.jpg 到 100.jpg。我想生成一个介于 1 - 100 之间的随机数,然后根据生成的数字在图像视图中显示相应的图像,例如随机数 5,因此显示 5.jpg。
我怎样才能做到这一点?谢谢!:-)
Random random = new Random();
// The +1 because nextInt(100) delivers between 0-99
int drawableNumber = random.nextInt(100) +1;
String drawableName = recourceNum + ".jpg";
yourImageView.setImageDrawable(getRecource().getDrawable(getRecources().getIdentifier(drawableName, "res/drawable", yourPackageName);
尝试这个:
oncreate(){
1- initialize your imageView say imgView.
2- generate a random number between 1 to 100, say random.
3- make sure you have all those 100 images in your res/drawable folder.
4- get the res ID related to the random by using following code:
int id = context.getResources().getIdentifier(String.valueOf(random), "drawable", context.getPackageName());
5- imgView.setImageResource(id);
}
希望这对你有帮助!!
private static int getRandomInteger(int aStart, int aEnd) {
long range = (long) aEnd - (long) aStart + 1;
long fraction = (long) (range * new Random().nextDouble());
int randomNumber = (int) (fraction + aStart);
return randomNumber;
}