Sunday, January 31, 2010

Setting width of Child View using Percentage

Category: UI
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.

5 comments:

  1. Actually, you can set the layout_width to wrap_content, and set the weight to 1, and they will be evenly distributed. No need for the .33.

    The way it works is simply to size everything that has no weight and is wrap_content first, then take the remaining space and split it between the weighted elements, using the weights to determine the proportions. So if you have three widgets with a weight of 1, they'll each get a third of the space; if you have 4 they'll each get a quarter. If you have one with a weight of 2 and two with a weight of 1, then the one with 2 will get twice the space of the other two.

    ReplyDelete
  2. thanks. very awesome! this tutorial provided great help for me!

    ReplyDelete
  3. Howard, the problem with setting the layout_width to "wrap_contents" is that if the contents are different widths (e.g. two buttons, "edit", & "delete"), first it wraps the contents, which results in different widths, and then it adds a equal amount of space to them. By setting the layout_width to "0dip", it makes them evenly spaced.

    ReplyDelete
  4. Helped me out big time! Thanks a lot!

    ReplyDelete