应用 LayoutParams 隐藏视图

Applying LayoutParams hides the View

下面的代码片段中有一行注释。当我取消注释该行时,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);

假设问题类似于 "What's the issue of this? How to resolve this?",这是我的答案:

当您将 LayoutParams 设置为 View 时,此 View 的父级将使用这些参数来适当地布局 View。因此,在您的情况下,您所做的如下:



    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(...);
    linearLayout.setLayoutParams(layoutParams);
    tableRow.addView(linearLayout);


现在,tableRow 很困惑,因为它期望 TableRow.LayoutParams 以便适当地布局视图,但它突然发现了一些其他布局参数。然而,如果您 没有 明确指定参数(即当 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);