这个问题实际上与这篇文章相关以编程方式设置 TextView 的布局权重
根据答案,我只需要如下设置 TextView 布局参数并设置stretchColumn 属性,但是通过将以下代码添加到我的代码中,它会使 textView 从表布局中消失。
TextView tv = new TextView(v.getContext());
tv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
所以,这是我的代码,我想动态添加一行 3 列,权重分别为 35%、5% 和 60%。请让我知道我的代码有什么问题。
private void addTableRow(int resIdTitle, String strValue){
TableRow tr = new TableRow(this);
// Add First Column
TextView tvTitle = new TextView(this);
tvTitle.setText(resIdTitle);
tvTitle.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 0.35f));
tr.addView(tvTitle);
// Add 2nd Column
TextView tvColon = new TextView(this);
tvColon.setText(" : ");
tvColon.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 0.05f));
tr.addView(tvColon);
// Add the 3rd Column
TextView tvValue = new TextView(this);
tvValue.setText(strValue);
tvValue.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 0.60f));
tr.addView(tvValue);
// Finally add it to the table
tl.addView(tr, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
Log.d(TAG, "Row Added");
}
这是我的 xml 文件,
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
<TableLayout
android:id="@+id/tl_cam_get_param"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:title="@string/strGetParamTitle"
android:scrollbars="vertical"
android:shrinkColumns="0">
</TableLayout>
</ScrollView>
我也尝试过将layout_width设置为0,但仍然不起作用。
Thanks,
艺术风格