Android 动态创建的表行之间的填充
我创建了一个TableLayout,然后在java代码中动态创建了TableRow,并以8x8网格的形式添加了一些按钮。但是我想减少按钮之间的空间。我尝试为TableRow设置LayoutParam,但当我这样做时,输出只显示一个空白屏幕。这是我的密码:Android 动态创建的表行之间的填充,android,android-tablelayout,tablerow,Android,Android Tablelayout,Tablerow,我创建了一个TableLayout,然后在java代码中动态创建了TableRow,并以8x8网格的形式添加了一些按钮。但是我想减少按钮之间的空间。我尝试为TableRow设置LayoutParam,但当我这样做时,输出只显示一个空白屏幕。这是我的密码: LayoutParams param= new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); field=new Button[8][8];
LayoutParams param= new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
field=new Button[8][8];
tb=new TableLayout(this);
param.setMargins(10, 2, 10, 2);
for (int i = 0; i < field.length; i++) {
TableRow current=new TableRow(this);
for (int j = 0; j < field[i].length; j++) {
Button button=new Button(this);
field[i][j]=button;
button.setWidth(40);
button.setHeight(40);
button.setLayoutParams(param);
current.addView(button);
}
tb.addView(current);
}
t.addView(tb);
LayoutParams param=新的LayoutParams(LayoutParams.FILL\u父级,LayoutParams.WRAP\u内容);
字段=新按钮[8][8];
tb=新的表格布局(本);
参数设置边距(10,2,10,2);
for(int i=0;i
但是当我不编写按钮时。setLayoutParams(param)
我得到如下输出:
这是正常的输出,只是我希望缩小按钮之间的间距。在param.setMargins()调用中,根据需要使用负值,以避开看起来是自然间距的部分。您还需要为表格布局提供相同的布局边距,并对宽度和高度使用换行内容。我不确定是否需要变量“t”,因为我在XML文件中使用TableLayout创建按钮时没有使用它。(我还做了一个5x5网格以适合我的屏幕。)
LayoutParams param=新的LayoutParams(LayoutParams.WRAP_内容,LayoutParams.WRAP_内容);
字段=新按钮[5][5];
tb=新的表格布局(本);
//这是两个重要的变化
参数设置边距(-5,-5,-5);
tb.setLayoutParams(参数);
for(int i=0;i
您看到的间距是标准Android按钮背景资源中内置的填充。通过在“设置”>“开发人员选项”中启用“显示布局边界”,可以看到布局是正确的。您只需要制作自己的按钮资源,或者如果只需要一种简单的颜色,则只需将按钮背景设置为一种颜色。只是猜测,但这只是更改param.setMargins()调用中的参数值吗?我希望如此,但它似乎对输出没有影响。这不是正确答案,按钮资产中只内置了填充;布局很好。感谢您提供的“显示布局边界”提示。我没有意识到,它看起来很有用。@kcopock谢谢,这不是我想要的,但它会很好用。
LayoutParams param= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
field=new Button[5][5];
tb=new TableLayout(this);
// these are the two important changes
param.setMargins(-5, -5, -5, -5);
tb.setLayoutParams(param);
for (int i = 0; i < field.length; i++) {
TableRow current=new TableRow(this);
for (int j = 0; j < field[i].length; j++) {
Button button=new Button(this);
field[i][j]=button;
button.setWidth(40);
button.setHeight(40);
button.setLayoutParams(param);
current.addView(button);
}
tb.addView(current);
}
t.addView(tb);