以编程方式添加的 EditText 没有设置 match_parent 宽度 属性

Programatically Added EditText does not has the match_parent width property set

我是 运行 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 似乎没有对 layout_width 有效的 match_parent 属性。我使用的 table 布局是

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

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

使用下面的代码

 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>

您为 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>