1

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

1 回答 1

2

假设问题类似于“这是什么问题?如何解决?” ,这是我的答案:

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



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


现在,它tableRow很困惑,因为它希望TableRow.LayoutParams适当地布局视图,但它突然发现了一些其他布局参数。然而,如果您没有明确指定参数(即 linearLayout.setLayoutParams()注释掉的时间),则会生成默认布局参数。



    @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);


于 2017-05-26T12:38:54.757 回答