2011-11-18 86 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