2013-04-29 26 views
3

我有一個整數0,1,2,3,4的列表。然後我洗牌,作爲第三步,我想初始化按鈕與第一個對象button1,第二個對象button2等 它的作品,如果我手動,但我想動態地解決它。如何動態解決這個隨機按鈕實現

List<Integer> objects = new ArrayList<Integer>(); 
      objects.add(0); 
      objects.add(1); 
      objects.add(2); 
      objects.add(3); 
      objects.add(4); 

     // Shuffle the collection 
    Collections.shuffle(objects); 

//this is not working here, but it should reflect what i am trying to achieve here 
// --> 
    for (int i = 0; i<objects.size(); i++) { 
     Button button**i** = (Button)findViewById(R.id.button**i**); 
     button**i**.setText(objects.get(i).toString()); 
    } 

在此先感謝。任何幫助讚賞(戳我的鼻子在正確的方向)

+0

什麼是不工作?你是否在'R.id.button ** i **'出錯? – 2013-04-29 11:10:28

+0

好吧,你不能在java中初始化一個變量variablename。 – bofredo 2013-04-29 11:11:51

+2

java不允許這樣做。您可以使用@fonZ答案... – 2013-04-29 11:14:36

回答

4

你可以通過洗牌你的按鈕列表解決這個問題。在迭代int時,它可以作爲混洗列表的索引。

像這樣:

List<Button> buttons = new ArrayList<Button>(); 
buttons.add((Button)findViewById(R.id.button0)); 
buttons.add((Button)findViewById(R.id.button1)); 
buttons.add((Button)findViewById(R.id.button2)); 
buttons.add((Button)findViewById(R.id.button3)); 
buttons.add((Button)findViewById(R.id.button4)); 

Collections.shuffle(buttons); 

for (int i = 0, s = 4; i < s; i++) { 
    buttons.get(i).setText("" + i); 
} 
+0

「at」 - 方法未定義列表

+0

更改爲:) – fonZ 2013-04-29 11:16:37

+1

值得注意的第一行可以簡化爲'列表 indexes = Arrays.asList(new int [] {0,1,2,3,4});' – 2013-04-29 11:18:51