android 动态添加button的问题
想动态添加一个10*10的button矩阵,写了如下代码,可是运行以后屏幕上还是空白一片,求助!
代码:
setContentView(R.layout.activity_game);
map = (TableLayout)findViewById(R.id.map);
blocks = new Button[10][10];
for(int row= 0;row<10;row++) {
for(int column= 0;column<10;column++) {
blocks[row][column] = new Button(this);
}
}
for(int row = 0;row<10;row++) {
TableRow tablerow = new TableRow(this);
tablerow.setLayoutParams(new LayoutParams(100, 10));
for(int column = 0;column<10;column++) {
blocks[row][column].setLayoutParams(new LayoutParams(10, 10));
blocks[row][column].setPadding(0, 0, 0, 0);
tablerow.addView(blocks[row][column]);
}
map.addView(tablerow,new TableLayout.LayoutParams(100,100));
}
xml:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".GameActivity" >
<TableRow>
<TableLayout
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TableLayout>
</TableRow>
</TableLayout>
[解决办法]
楼主先试试addView一定要用带两个参数的函数,也就是改两句:
TableRow.LayoutParams lp = new TableRow.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
tablerow.addView(blocks[row][column], lp);
........
map.addView(tablerow,new TableLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
如果还是不行,对所有控件先不要setLayoutParams(),而是在addView(),第二个参数的设置为指定的高度和宽度,例如:
tablerow.addView(blocks[row][column], new LayoutParams(10, 10));
.....
map.addView(tablerow,new TableLayout.LayoutParams(100,10));
注意:addView一定要用带两个参数的函数