Subcategory: LinearLayout, Style
Android Platform: 1.5, Google APIs 3
Referenced Classes: android.widget.LinearLayout, android.widget.TextView
There have been cases where I needed to the set the width of a Child View using percentage, as opposed to dimension value (i.e. pixel). As an example, I wanted three TextViews of equal width to be contained in a horizontal LinearLayout, filling an entire row. Consequently, each TextView would need to have a width of 33%. In HTML, a simple way to do this would be:
code snippet
<table width="100%">
<tr>
<td width="33%">...</td>
<td width="33%">...</td>
<td width="33%">...</td>
</tr>
...
...
In Android, this can be done by using android:weightSum, android:layout_weight, and android:layout_width:code snippet
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:weightSum="1.0">
<TextView
android:id="@+id/textbox1"
android:layout_height="wrap_content"
android:layout_weight=".33"
android:layout_width="0dip"
android:textSize="12sp" />
<TextView
android:id="@+id/textbox2"
android:layout_height="wrap_content"
android:layout_weight=".33"
android:layout_width="0dip"
android:textSize="12sp" />
<TextView
android:id="@+id/textbox3"
android:layout_height="wrap_content"
android:layout_weight=".33"
android:layout_width="0dip"
android:textSize="12sp" />
</LinearLayout>
Note, that android:layout_width must be set to 0 for android:layout_weight to be effective.