2010-07-23 92 views
3
String rank[] = {"tclub1.png", "tclub2.png", "tclub3.png", "tclub4.png", 
    "tclub5.png", "tclub6.png", "tclub7.png", "tclub8.png", "tclub9.png", 
    "tclub10.png", "tclub11.png", "tclub12.png", "tclub13.png"}; 

Random randInt = new Random(); 
int b = randInt.nextInt(rank.length); 
String d = ("tclub" + b + ".png"); 
Log.v(LOG_TAG, "in value:=" + d); 

以上是代碼。 其實我的數組給我一個(0到12)之間的隨機索引..之後,我將它附加到一個圖像名稱。例如(tclub1.png) 現在它給我的圖像名稱是String fromat。 我如何隨機指定這個圖像?Android隨機

+0

http://stackoverflow.com/questions/3315718/android-random-number – fadden 2010-07-23 19:27:47

回答

1

如果您想將圖像加載到ImageView的,你可以這樣做:

String imgName = "tclub1"; // the image you want to load 
int id = getResources().getIdentifier(imgName, "drawable", getPackageName()); 
imageView.setImageResource(id); 
+0

的重複喜itsik .. thanks..but它沒有發生。 當我使用日誌標籤來查看它顯示的ID的值0 nd不隨機設置圖像 – 2010-07-23 09:26:54

+1

所有的圖像位於res/drawable?此外,圖片名稱應該沒有「.png」。 (它應該只是資源名稱) – Itsik 2010-07-23 10:07:08

+0

是所有圖像都在drawable-hpdi文件夾中。 – 2010-07-23 10:17:54

0

找到控制:

ImageView image = (ImageView) findViewById(R.id.rockId); 

要動態地從繪製加載圖像我用這個幫手函數

public static int getDrawable(Context context, String name) 
{ 
    Assert.assertNotNull(context); 
    Assert.assertNotNull(name); 

    return context.getResources().getIdentifier(name, 
      "drawable", context.getPackageName()); 
} 

這將返回您的drawable的id,現在您只需要設置imag E在控制:

image.setImageResource(int Id);