我试图使桌子上装满按钮,然后将按钮均匀地分布在桌子上。但是,当我这样做时,按钮不会显示完整的高度,看起来像这样:https://imgur.com/a/L3c5Yrk
这是我用于创建表的代码。我已经手动创建了表格视图,但是必须以编程方式创建按钮和表格行。
/* Find Tablelayout defined in main.xml */
TableLayout tl = findViewById(R.id.gameBoard);
/* Create a new row to be added. */
for (int j = 0; j < 3; j++) {
TableRow tr = new TableRow(this);
tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
/* Create a Button to be the row-content. */
for (int i = 0; i < 3; i++) {
final Button b = new Button(this);
b.post(new Runnable() {
@Override
public void run() {
TableLayout myTableLayout = findViewById(R.id.gameBoard);
int width = myTableLayout.getWidth();
int height = myTableLayout.getHeight();
ViewGroup.LayoutParams params = b.getLayoutParams();
params.height = (height - (10 * 4))/3;
params.width = (width - (10 * 4))/3;
b.setLayoutParams(params);
}
});
b.setText("Dynamic Button");
b.setBackgroundColor(Color.parseColor("#FFFFFF"));
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics());
float xPixel = px * (1 + i);
float yPixel = px * (1 + j);
b.setX(xPixel);
b.setY(yPixel);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
flip(v);
}
});
b.setId(i + (j * 3));
buttons.add(b);
/* Add Button to row. */
tr.addView(b);
}
/* Add row to TableLayout. */
//tr.setBackgroundResource(R.drawable.sf_gradient_03);
tl.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
}