【发布时间】:2019-12-13 19:25:56
【问题描述】:
尝试在 Android 中做一个动态的 TableLayout。
在我的布局中只有这个:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_table"
android:orientation="vertical"
android:background="@android:color/background_dark"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:keepScreenOn="true">
</TableLayout>
我想动态地将行(和列)添加到这个表中,因为在编译时不知道我需要显示多少个单元格。
但可以肯定的是,整个表格必须适合屏幕(实际上适合并拉伸)。
我也为行创建了一个布局(现在有 2 个固定单元格):
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:text="Rate User1"
/>
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:text="Rate User2"
/>
</TableRow>
在活动的 onCreate 函数中,我正在充气 3 行,我希望它们遍布整个屏幕:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater inflater = getLayoutInflater();
TableLayout tableLayout = findViewById(R.id.main_table);
TableRow.LayoutParams rowParams = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, 0, 1f /*0.33f*/);
TableRow tableRow1 = (TableRow)inflater.inflate(R.layout.item_stream_row, tableLayout, false);
tableRow1.setLayoutParams(rowParams);
TableRow tableRow2 = (TableRow)inflater.inflate(R.layout.item_stream_row, tableLayout, false);
tableRow2.setLayoutParams(rowParams);
TableRow tableRow3 = (TableRow)inflater.inflate(R.layout.item_stream_row, tableLayout, false);
tableRow3.setLayoutParams(rowParams);
//tableLayout.setWeightSum(1f);
tableLayout.addView(tableRow1);
tableLayout.addView(tableRow2);
tableLayout.addView(tableRow3);
}
但现在行高与其内容相匹配,而不是拉伸到整个屏幕:
如果我注释掉 addViews,并将 3 个 TableRows 放入主布局中,它看起来就像我想要的那样:
所以问题是,如果不能将行直接放入布局文件中,我该如何实现我想要的结果(第二张图片)?
【问题讨论】:
标签: android android-layout android-tablelayout