【问题标题】:Programatically Added EditText does not has the match_parent width property set以编程方式添加的 EditText 没有设置 match_parent 宽度属性
【发布时间】:2015-01-20 14:39:00
【问题描述】:

我在 for 循环中运行以下代码。

TableRow r1 = new TableRow(this);
r1 .setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));

TextView editLabel = new TextView(this);
editLabel.setText("Label");
EditText editText = new EditText(this);
editText.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
editText.setMaxLines(1);

r1.addView(editLabel);
r1.addView(editText);
tableLayout1.addView(r1);

行被添加到 TableLayout 但 EditText 似乎没有 match_parent 属性对 layout_width 有效。我使用的表格布局是

<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="0"
android:shrinkColumns="1"
android:id="@+id/attibutesLayout">
</TableLayout>

edittext 的宽度似乎为零,并且随着我输入数据而不断增加。我希望编辑文本具有恒定的宽度以适合列内。

【问题讨论】:

标签: android android-layout android-edittext


【解决方案1】:

使用下面的代码

 TableRow r1 = new TableRow(this);
    r1 .setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
    final float scale = this.getResources().getDisplayMetrics().density;
    TextView editLabel = new TextView(this);
    editLabel.setLayoutParams(new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT,(int) (1 * scale + 0.5f)));
    editLabel.setText("Label");
    EditText editText = new EditText(this);
    editText.setLayoutParams(new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT,(int) (1 * scale + 0.5f)));
    editText.setMaxLines(1);
    r1.addView(editLabel);
    r1.addView(editText);
    tableLayout1.addView(r1);

你的xml是一样的

<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="0"
android:shrinkColumns="1"
android:id="@+id/attibutesLayout">
</TableLayout>

【讨论】:

  • 如果我将拉伸列设为“1”,那么宽度将不是一个常数。当我输入更多文本时,宽度会增加
  • 那么你必须将每个 View 的 layout_width 设置为 0,并将 tablerow 元素的权重设置为 1
  • 使用我的更新答案以编程方式设置宽度和重量
【解决方案2】:

您为 TableLayout stretchColumns 设置了错误的值,将其更改为 1 应该可以解决您的问题。使用以下布局并尝试一下:

<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="1"
android:shrinkColumns="1"
android:id="@+id/attibutesLayout">
</TableLayout>

【讨论】:

    猜你喜欢
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 2016-12-16
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    • 2012-07-30
    相关资源
    最近更新 更多