2017-02-19 81 views
-3

我有150張圖片,我可以如何將它們中的一個設置爲ImageButton,具體取決於隨機生成的ID? [代碼更新】 我開始這樣的:如何隨機設置ImageButton?

int x, y, z,resID; 
String sID; 
Random rand; 
ImageButton SButton; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_play_); 
    rand = new Random(System.currentTimeMillis()); 
    SButton = new ImageButton(this); 
    SButton.setVisibility(View.VISIBLE); 
} 

public void Start(View view) { 
    SButton = (ImageButton) view; 
    x = rand.nextInt(3); 
    y = rand.nextInt(8); 
    z = rand.nextInt(10); 
    sID = "shape_" + x + y + z; 
    resID =getResources().getIdentifier(sID,"drawable","com.packagename"); 
    SButton.setImageResource(resID); 
} 

與爲我工作的代碼更新

+0

所有圖片都有自己的ID,這就是他們的名字:'R.drawable.image1','R.drawable.image2'等。爲什麼你需要他們有隨機ID? – JonZarate

+0

正如我所說我是新來的Android,對不起... [更新了問題]我有我的隨機選擇的ID如何設置圖像按鈕完全一樣隨機生成的ID? @JonZarate –

+0

你想用ImageButton的隨機ID做什麼? – tash

回答

0

您可以通過下面的代碼做到這一點:

int resource = getResources().getIdentifier(myID, "drawable", "com.your.package"); 

PS:取從名稱中刪除「R.id.」。

+0

我已更新我的代碼,謝謝@Atabtab Hussain –

+0

它工作了weel,但它給出了這個錯誤** getSlotFromBufferLocked:未知的緩衝區錯誤** @Aftab Hussain –

+0

顯然,這是Marshmellow的一個公開問題。看看'Itai Hanski'的回答在 http://stackoverflow.com/questions/32561479/android-studio-getslotfrombufferlocked-unknown-buffer-error –

0
  1. 重命名像image1,image2,...,image150的yuor圖像。

  2. 生成在1 150之間(包括兩端)的隨機數。下面的代碼

  3. 用它來獲得圖像資源ID。 (使用「紋理貼圖」,而不是「繪製」如果你放在紋理貼圖文件夾中的圖片)

    String myID = "image"+ generatedRandomNumber; 
    int resource = getResources().getIdentifier(myID, "drawable", "com.your.package"); 
    
  4. 使用該資源ID來設置圖像ImageButton