将java按钮添加到LinearLayout

时间:2013-07-18 23:47:01

标签: java android onclicklistener

我正在制作一个Gomoku程序的问题(在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);

            }

        }

    }
}

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

帮助会很棒:D

2 个答案:

答案 0 :(得分: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);

        }

    }

}

答案 1 :(得分:0)

向布局添加按钮......

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]);
         }

    }