【问题标题】:Applying LayoutParams hides the View应用 LayoutParams 隐藏视图
【发布时间】:2017-05-26 12:24:18
【问题描述】:

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

【问题讨论】:

  • 也许您忘记为文本视图添加布局参数?我认为现在 TextView 的宽度和高度为 0dp,而 linearLayout 具有 match_parent 参数,因此您看到的是空视图
  • 当我使用textLabel.setHeight(20); textLabel.setWidth(20) 时它也不显示
  • 尝试更改linearLayout的layoutParams源 new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
  • 感谢您的提示。我现在尝试使用LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);,但它仍然没有出现。

标签: android android-layout android-view android-tablelayout android-layoutparams


【解决方案1】:

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

当您将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);

【讨论】:

    猜你喜欢
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多