2013-02-18 123 views
0

我試圖設置5(五)按鈕編號的編號,並隨機洗牌。
洗牌沒有問題。

當我使用2(2)方法洗牌並設置5個按鈕的ID並設置每個按鈕的文本時,我會收到錯誤。
我知道這可能是一團糟,因爲這是我第一次嘗試 - 每個循環。
請幫忙。謝謝。如何通過循環設置按鈕ID的數組並使用循環設置按鈕文本?

Button b1, b2, b3, b4, b5; 
Button[] buttons = { b1, b2, b3, b4, b5 }; 

    public void shuffleButtons() { 

      Integer[] Id = { R.id.bChoice1, R.id.bChoice2, R.id.bChoice3, 
        R.id.bChoice4, R.id.bChoice5 }; 

      ArrayList<Integer> buttonId = new ArrayList<Integer>(Arrays.asList(Id)); 

      Collections.shuffle(buttonId); 


       for (int x = 0; x < 5; x++) { 

        for (Button b : buttons) { 

         b = (Button) findViewById(buttonId.get(x)); 

        } 

       } 


     } 

public void setButtonTxt() { 


      for (Button b : buttons) { 

       for (int x = 0; x <= buttons.length; x++) { 

        b.setText(textList.get(x)); 

       } 
      } 

    } 
+0

爲什麼不使用listView呢?這可能更適合這一點。 – 323go 2013-02-18 20:50:59

回答

0

總之,我猜你的問題是x <= buttons.length應該是你的for循環中的x < buttons.length。然而,它看起來像你將使用當前的代碼將所有5個按鈕設置爲textList.get(5)

爲什麼不嘗試使用XML中的預設按鈕?

<Button android:id="@+id/bChoice1" ... /> 
<!-- etc --> 
<Button android:id="@+id/bChoice5" ... /> 

然後在後面的代碼中,隨機化文本而不是兩者?

Button b1 = (Button)findViewById(R.id.bChoice1); 
Button b2 = (Button)findViewById(R.id.bChoice2); 
Button b3 = (Button)findViewById(R.id.bChoice3); 
Button b4 = (Button)findViewById(R.id.bChoice4); 
Button b5 = (Button)findViewById(R.id.bChoice5); 

// assuming textList is an ArrayList of text items 
// the next two lines will randomize your textList order 
// so you don't need to do it yourself and much less 
// error-prone 
long seed = System.nanoTime(); 
Collections.shuffle(textList, new Random(seed)); 

b1.setText(textList.get(0)); 
b2.setText(textList.get(1)); 
b3.setText(textList.get(2)); 
b4.setText(textList.get(3)); 
b5.setText(textList.get(4)); 
+0

好的。我會嘗試。謝謝!順便說一句,我沒有得到那個'長'變量與集合。這兩行代碼。 – ejmtv 2013-02-18 20:33:39

+0

在中添加註釋。基本上隨機化textList ArrayList的順序 – Kirk 2013-02-18 20:47:05

2

我想設置的五(5)按鈕ID的編程和 每次洗牌它們。洗牌沒有問題。

我的建議是你不應該這樣做。每個ID應該從XML創建,然後在R.java中自動生成爲靜態int字段。

你應該尊重這個規則,不要創建「意大利麪代碼」。

0

這是更好地爲你寫你的代碼是這樣的:

Button [] buttens=new Button[5]; 
final int ID= R.id.bChoice1; 
for (int i = 0; i < 5; i++) { 
     button[i]=(Button)findViewById(ID+i); 
    } 

但要小心,它的工作原理,只要你設定按鈕的ID的連續!