android - 应用 LayoutParams 隐藏 View

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

在下面的代码 fragment 中,有一行注释。当我取消注释该行时,LinearLayout 的内容不会显示在 TableRow 中。在不设置 LayoutParams 的情况下,该行显示两个文本。我不明白这种行为。我知道我可以通过 xml 文件包含复杂的 View ,但我更想了解这段代码有什么问题:

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

最佳答案

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

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



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


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


关于android - 应用 LayoutParams 隐藏 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44201558/

相关文章:

java - 更新 ParseUser 字段

android - 无法创建径向渐变

android - 如何在android中添加多个值:tag

Android:getApplicationContext() 在 View 子类中不起作用

android - 仅当空间足够时才在右侧查看,否则在底部

android - 无法解析权限符号

android - 将子文件夹添加到 android studio 1.0.2 中的 java 文件夹

android - 键盘将 EditText 隐藏在 android 中的 ScrollView 中?

android - Canvas 不显示图像/可绘制

android - 在每天的特定时间设置开机时间警报