我正在与Android的糟糕布局系统作斗争。我正在尝试用一张桌子填满屏幕(很简单吗?),但是很难做到。
我得到它可以以某种方式在XML中工作:
<?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent" android:layout_width="fill_parent"> <TableRow android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="1"> <Button android:text="A" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1"/> <Button android:text="B" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1"/> </TableRow> <TableRow android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="1"> <Button android:text="C" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1"/> <Button android:text="D" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1"/> </TableRow>
但是我无法使其在Java中工作。我已经尝试了LayoutParams的一百万种组合,但是没有任何效果。这是我得到的最佳结果,它只能填充屏幕的宽度,而不是高度:
table = new TableLayout(this); // Java. You suck. TableLayout.LayoutParams lp = new TableLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT); table.setLayoutParams(lp); // This line has no effect! WHYYYY?! table.setStretchAllColumns(true); for (int r = 0; r < 2; ++r) { TableRow row = new TableRow(this); for (int c = 0; c < 2; ++c) { Button btn = new Button(this); btn.setText("A"); row.addView(btn); } table.addView(row); }
显然,Android文档没有帮助。有人有主意吗?
终于弄清楚了如何做到这一点。放弃TableLayout并只LinearLayout在垂直的s中使用了水平的s。关键是设置重量。如果您指定FILL_PARENT但使用默认权重,则无法使用:
TableLayout
LinearLayout
FILL_PARENT
LinearLayout buttonsView = new LinearLayout(this); buttonsView.setOrientation(LinearLayout.VERTICAL); for (int r = 0; r < 6; ++r) { LinearLayout row = new LinearLayout(this); row.setOrientation(LinearLayout.HORIZONTAL); for (int c = 0; c < 4; ++c) { Button btn = new Button(this); btn.setText("A"); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); lp.weight = 1.0f; row.addView(btn, lp); } LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); lp.weight = 1.0f; buttonsView.addView(row, lp); } ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT); setContentView(buttonsView, lp);