我正在尝试创建一个包含16 x 16按钮的GridLayout,但我无法删除按钮之间的空格。
我看到了this,但它没有用。
以下是我现在正在尝试的内容:
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
GridLayout v = (GridLayout)findViewById(R.id.myGrid);
v.setPadding(0, 0, 0, 0);
v.setUseDefaultMargins(false);
v.setAlignmentMode(GridLayout.ALIGN_BOUNDS);
v.setRowOrderPreserved(false);
Random r = new Random();
for (int row = 0; row < 16; row++)
for (int col = 0; col < 16; col++) {
GridLayout.LayoutParams lp = new GridLayout.LayoutParams();
lp.setMargins(0, 0, 0, 0);
lp.rowSpec = GridLayout.spec(row);
lp.columnSpec = GridLayout.spec(col);
lp.width = 40;
lp.height = 40;
Button b = new Button(this);
b.setWidth(40);
b.setHeight(40);
b.setText(Integer.toString(r.nextInt(10)));
b.setPadding(0, 0, 0, 0);
b.setLayoutParams(lp);
v.addView(b, lp);
}
}
截图
知道什么是错的吗?
编辑:我将一些按钮的背景改为绿色图片这是我得到的:显然间距是按钮图像的一部分...为什么是Android,为什么?
答案 0 :(得分:0)
因为您希望每个项目都有固定的宽度和固定的高度,所以这里出错了。试试这个:
GridLayout.LayoutParams lp = new GridLayout.LayoutParams();
lp.setMargins(0, 0, 0, 0);
lp.rowSpec = GridLayout.spec(row);
lp.columnSpec = GridLayout.spec(col);
//lp.width = 40;
//lp.height = 40;
Button b = new Button(this);
//b.setWidth(40);
//b.setHeight(40);
b.setText(Integer.toString(r.nextInt(10)));
b.setPadding(0, 0, 0, 0);
b.setLayoutParams(lp);
v.addView(b, lp);
}