我在做一个用java创建View的程序,我想要表格按钮。我不明白发生了什么。
这是代码:
公共类Snake扩展了Activity {
LinearLayout layout [] = new LinearLayout[10];
Button boton[][] = new Button [10][10];
LinearLayout snake = (LinearLayout) findViewById(R.id.snake);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snake);
//LayoutParams fillWrap = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
// LayoutParams wrapWrap = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
for (int i = 0; i < layout.length; i++) {
layout [i] = new LinearLayout(this);
layout[i].setId(i);
layout[i].setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
snake.addView(layout[i]);
for (int j = 0; j < layout.length; j++) {
boton[i][j] = new Button(this);
boton[i][j].setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
if ((i == 5) && (j ==5)) {
boton[i][j].setBackgroundColor(Color.RED);
} else {
boton[i][j].setBackgroundColor(Color.BLUE);
}
layout[i].addView(boton[i][j]);
}
}
}
}
谢谢
答案 0 :(得分:0)
您错过了布局方向。您还需要设置layoutparams width LayoutParams.MATCH_PARENT
layout[i].setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
layout[i].setOrientation(LinearLayout.HORIZONTAL);