使用情景:TableLayout、TableRow及其内的button控件width都设为android:layout_width="match_parent"
,但button不填充满宽度,实际显示如下:
代码如下:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</TableRow>
</TableLayout>
原因:在表格布局中,列默认不可拉伸,即使设置android:layout_width="match_parent"
,显示效果为上图。若要使列控件填充整行,则在TableLayout
属性中配置android:stretchColumns=""
。
android:stretchColumns属性:
功能:设置允许被拉伸的列的序列号(序列号从0开始),多个序列号中间用“,”分隔。
如上的代码只需在TableLayout中增加属性android:stretchColumns="0"
即可,效果如下:
更改后代码如下:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="0">
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</TableRow>
</TableLayout>