尝试在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);
}
但是现在行高匹配其内容,而不是延伸到整个屏幕:
如果我注释掉addView,然后将3个TableRows放入主布局中,则看起来像我想要的一样:
所以问题是,如果不能将行直接放入布局文件中,怎么能达到我想要的结果(第二张图像?
解决方案是更改TableRow的LayoutParams: