match_parent不填充父级!

时间:2011-01-05 10:13:20

标签: android-layout

我在TableRow中有LinearLayout。 LinearLayout以这种方式在代码中启动:

LinearLayout  mainRowLayout = new LinearLayout(this);
mainRowLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
TableRow tr = new TableRow(this);
tr.addView(mainRowLayout);

问题是LinearLayout没有填充父级(即TableRow)。 附图说明了问题,如Android的hirarchyViewer所示(绿色矩形是我的标记)。

"LinearLayout image"

感谢。

1 个答案:

答案 0 :(得分:13)

以编程方式创建布局时,您需要为父容器提供子项的布局说明。

// child element
LinearLayout mainRowLayout = new LinearLayout(this);

// parent element
TableRow tr = new TableRow(this);

// parent element's instructions (layout params for main row)
TableRow.LayoutParams lopForMainRow = new TableRow.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);

tr.addView(mainRowLayout, lopForMainRow);

试一试:]