【问题标题】:Adding java button to LinearLayout将java按钮添加到LinearLayout
【发布时间】:2013-07-18 23:47:00
【问题描述】:

我正在制作的五子棋程序有问题(在 10x10 板上连续 5 个)。我正在尝试实现从我的 Game.java 到我的 game.xml 的 10x10 按钮数组。这是我目前拥有的代码

   public class Game extends Activity implements View.OnClickListener{
    private boolean p2Turn = false;
    private char board[][] = new char[10][10];
    Context c;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.game);
        Button btn[][] = new Button[10][10];
        for(int i = 0; i<10; i++){
            for(int j = 0; j<10; j++){
                btn [i][j] = new Button(this);

            }

        }

    }
}

但是我不知道如何在我的 game.xml 中实现 10x10 按钮数组

帮助会很棒:D

【问题讨论】:

标签: java android onclicklistener


【解决方案1】:

按钮已创建但未放置在任何位置。这可能会有所帮助

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity);
    final LinearLayout container = (LinearLayout)findViewById(R.id.container where you want to place your buttons);

    Button btn[][] = new Button[10][10];
    for(int i = 0; i<10; i++){
        for(int j = 0; j<10; j++){
            btn [i][j] = new Button(this);
            btn[i][j].setText("Button "+i);

            container.addView(btn[i][j],i);

        }

    }

}

【讨论】:

    【解决方案2】:

    在布局中添加按钮...

    ViewGroup layout = (ViewGroup) findViewById(R.layout.game);
         Button btn[][] = new Button[10][10];
          for(int i = 0; i<10; i++){
               for(int j = 0; j<10; j++){
                 btn [i][j] = new Button(this);
                  layout.addView(btn [i][j]);
             }
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多