在下面的代码段中,有一条注释行。当我取消注释该行时,LinearLayout
的内容不会显示在TableRow
中。如果不设置LayoutParams
,该行将显示两个文本。我不明白这种行为。我知道我可以通过xml
文件添加复杂的观看次数,但我更了解这段代码的错误:
TableLayout tableLayout = (TableLayout) findViewById(R.id.table);
TableRow tableRow = new TableRow(this );
tableRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT);
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
// when I comment out this line, the row only shows the second text.
// linearLayout.setLayoutParams(layoutParams);
TextView textLabel = new TextView(this);
textLabel.setText("inside linear layout");
linearLayout.addView(textLabel);
TextView message = new TextView(this);
message.setText( "inside tablerow");
tableRow.addView(linearLayout);
tableRow.addView(message);
tableLayout.addView(tableRow);
答案 0 :(得分:2)
假设问题类似于“这是什么问题?如何解决这个问题?”,这是我的回答:
当您将LayoutParams
设置为View
时,此View
的父级将使用这些参数来正确布局View
。所以在你的情况下你所做的是:
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(...);
linearLayout.setLayoutParams(layoutParams);
tableRow.addView(linearLayout);
现在,tableRow
很困惑,因为它需要TableRow.LayoutParams
才能正确布局视图,但它会突然发现其他一些布局参数。然而,如果您不明确指定了params(即当linearLayout.setLayoutParams()
被注释掉时),则默认布局参数would be generated。
@Override
protected LinearLayout.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(); // this is TableRow.LayoutParams
}
因此,创建LinearLayout.LayoutParams
:
TableRow.LayoutParams
TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(...);
linearLayout.setLayoutParams(layoutParams);
tableRow.addView(linearLayout);