2011-11-18 85 views
0

我有這樣的功能:設置按鈕文本不起作用

public void setRandomValuesToButtons() { 

    for(i=0;i<Rows; i++){ 
     for(j=0;j<Columns; j++){ 
      if (i==2 && j==1){ 
       continue; 
      } 
      // Random rand = new Random(); rand global variable 
      rand_int = rand.nextInt(8);  


      buttonsTable[i][j]=new Button(this); 
      buttonsTable[i][j].setText(Integer.toString(rand_int)); 
      buttonsVals[i][j]=rand_int; 
     } 
    } 

但我的按鈕並沒有改變他們的文本。爲什麼?

+0

這是什麼時候運行?在調用setRandomValuesToButtons()之前調用setRandomValuesToButtons(),我初始化每個按鈕,如下所示: buttonsTable [0] [1] =(Button)findViewById(R.id.B_l0c1); – fredley

回答

2

因爲您的按鈕不可見。

您正在通過調用new Button(this)來創建新的Button實例,但實際上並未使用ViewGroup.addView()將它們添加到可見佈局中。如果它們不屬於佈局,則不會顯示。

您可能想要使用findViewById()在您的佈局中查找現有的按鈕而不是創建新的按鈕(我假設您的按鈕已經在屏幕上可見)

+0

現在,如果我刪除行「buttonsTable [i] [j] = new Button(this);」 然後我得到消息「應用程序意外停止」 – user1047069

+0

這意味着'findViewById()'最有可能返回'null',因爲無法找到具有該特定ID的視圖/按鈕。確保在使用'findViewById()'之前調用'setContentView()',這是一個常見的錯誤。如果你沒有設置佈局/內容視圖,'findViewById()'找不到任何東西,因爲它在顯示的UI層次中搜索。 – 2011-11-18 12:59:13

+0

明白了,謝謝。 – user1047069