我正在与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文档无济于事。有谁有什么想法吗?
发布于 2010-03-20 08:36:16
我终于想出了怎么做。放弃了TableLayout
,只在垂直LinearLayout
中使用了水平a。关键是设置权重。如果指定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);
发布于 2010-03-08 19:24:40
找到了答案:显然是layout_weight让它工作,没有办法从Java语言中设置它。该死的。
请参阅How can I get an Android TableLayout to fill the parent in landscape mode?
发布于 2010-03-07 04:35:46
您永远不会设置行或按钮布局参数,而在发布的xml中,您需要使用that..change循环的细节来设置行布局参数和按钮布局参数,这样做的结果应该与您的xml相同。
https://stackoverflow.com/questions/2393847
复制相似问题