Tuesday, November 22, 2011

TableLayout columns equal width

Something easy like columns of equal width in a TableLayout shouldn't be difficult. It's not, but there is a trick to getting the desired layout. layout_width="0dip" and layout_weight="1" tags must be set in your XML layout. Here's an example:



<tablelayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1">

<TableRow>
<!-- Column 1 -->
<TextView
android:id="@+id/tbl_txt1"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:background="@color/red"
android:textColor="@color/white"
android:padding="10dip"
android:layout_margin="4dip"
android:layout_weight="1"
android:text="Column 1" />

<!-- Column 2 -->
<TextView
android:id="@+id/tbl_txt2"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:background="@color/red"
android:textColor="@color/white"
android:padding="10dip"
android:layout_margin="4dip"
android:layout_weight="1"
android:text="Column 2" />

<!-- Column 3 -->
<TextView
android:id="@+id/tbl_txt3"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:background="@color/red"
android:textColor="@color/white"
android:padding="10dip"
android:layout_margin="4dip"
android:layout_weight="1"
android:text="Column 3" />
</TableRow>
</TableLayout>