Android 在TableLayout中动态调整TextView宽度

Android 在TableLayout中动态调整TextView宽度,android,textview,android-tablelayout,Android,Textview,Android Tablelayout,我动态地创建了一个表,其中填充了不同长度的键和值 当我试图将宽度设置为包裹内容时,宽度是相对于单个键大小而不是整个表设置的 这将导致在表中添加较大宽度的键后,第二个TextView的宽度过大 我尝试在完成后重新绘制表格,但保留了原始的TextView宽度 是否有一个我忽略的简单修复,或者我需要通过编程获得最长的键宽度,然后手动设置第二个文本视图的最大宽度 layout.xml <ScrollView android:layout_width="fill_parent" an

我动态地创建了一个表,其中填充了不同长度的键和值

当我试图将宽度设置为包裹内容时,宽度是相对于单个键大小而不是整个表设置的

这将导致在表中添加较大宽度的键后,第二个TextView的宽度过大

我尝试在完成后重新绘制表格,但保留了原始的TextView宽度

是否有一个我忽略的简单修复,或者我需要通过编程获得最长的键宽度,然后手动设置第二个文本视图的最大宽度

layout.xml

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:scrollbars="none">

    <TableLayout
        android:id="@+id/passData"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="15dip">
    </TableLayout>
</ScrollView>
结果


您可以使用此自动调整大小文本视图解决您的问题


解决方案只是向LayoutParams添加一个权重,并将宽度设置为零,以使其大小正确

activity.java

private TableRow generateRow(String key, String value, boolean isOdd) {

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

    if (isOdd) {
        tr.setBackgroundColor(getResources().getColor(R.color.colorTableRow));
    }

    TextView keyView = new TextView(this);
    TextView valueView = new TextView(this);

    keyView.setTypeface(null, Typeface.BOLD);
    keyView.setPadding(30, 20, 30, 20);
    keyView.setTextSize(15);
    keyView.setText(firstCaps(key));

    valueView.setText(value.replace(" ", "\u00A0"));
    valueView.setSingleLine(false);
    valueView.setMaxLines(20);
    valueView.setPadding(0, 20, 30, 20);
    valueView.setGravity(Gravity.CLIP_HORIZONTAL);

    tr.addView(keyView);
    tr.addView(valueView,new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,     
TableRow.LayoutParams.WRAP_CONTENT));

    return tr;
}
private TableRow generateRow(String key, String value, boolean isOdd) {
    TableRow tr = new TableRow(this);
    tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, 
TableRow.LayoutParams.WRAP_CONTENT));
    if (isOdd) {
        tr.setBackgroundColor(getResources().getColor(R.color.colorTableRow));
    }
    TextView keyView = new TextView(this);
    TextView valueView = new TextView(this);

    keyView.setTypeface(null, Typeface.BOLD);
    keyView.setPadding(30, 20, 30, 20);
    keyView.setTextSize(15);
    keyView.setText(firstCaps(key));
    valueView.setText(value);
    valueView.setSingleLine(false);
    valueView.setMaxLines(20);
    valueView.setPadding(0, 20, 30, 20);
    tr.addView(keyView);

    // Set width to zero and weight to 1
    tr.addView(valueView,new TableRow.LayoutParams(0, 
        TableRow.LayoutParams.WRAP_CONTENT, 1f));

    return tr;
}
结果


由于文本视图的宽度已设置,因此不确定该操作是否有效。将于明天尝试并让您知道。正如所怀疑的那样-文本视图的大小已相对于行中其他文本视图的宽度确定。因此,这类课程没有任何效果。