2012-07-16 70 views
0

我在原始文件夾中有一堆圖像,名稱範圍從1.jpg到100.jpg。我想生成一個介於1 - 100之間的隨機數,然後根據生成的數字顯示圖像視圖中的相應圖像,例如隨機數字5如此顯示5.jpg。在圖像視圖中顯示隨機jpg

我該怎麼做?謝謝! :-)

+0

你試過了什麼? – 2012-07-16 08:57:31

回答

0

試試這個:

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); 

} 

希望這可以幫助你!

1
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); 
-1
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; 
}