我在原始文件夾中有一堆圖像,名稱範圍從1.jpg到100.jpg。我想生成一個介於1 - 100之間的隨機數,然後根據生成的數字顯示圖像視圖中的相應圖像,例如隨機數字5如此顯示5.jpg。在圖像視圖中顯示隨機jpg
我該怎麼做?謝謝! :-)
我在原始文件夾中有一堆圖像,名稱範圍從1.jpg到100.jpg。我想生成一個介於1 - 100之間的隨機數,然後根據生成的數字顯示圖像視圖中的相應圖像,例如隨機數字5如此顯示5.jpg。在圖像視圖中顯示隨機jpg
我該怎麼做?謝謝! :-)
試試這個:
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);
}
希望這可以幫助你!
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);
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;
}
你試過了什麼? – 2012-07-16 08:57:31