Monday, July 25, 2011

android:layout_weight="1"

A common ui layout used in Android development is the Linear Layout.  It does what its name suggests and lays out its child views (ui elements) sequentially, in either a vertical or horizontal orientation (as specified by the android:orientation attribute).  As a developer, you can choose to specify the sizes of your views or let the OS take care of them for you (by specifying either "wrap_content" or "fill_parent" / "match_parent" for the layout_height / layout_width values).

Let's consider a full screen ui where we have a header containing the title of our content, a footer with one button in it, and a text description which occupies the rest of the space (e.g. a product description view in a shopping app).

We could define said layout as:

<LinearLayout

  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical">


  <TextView
    android:layout_width="fill_parent"

    android:layout_height="wrap_content"
    android:text="Title" />


  <TextView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="Some description of our content" />


  <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="OK" />

</LinearLayout>


We have defined a LinearLayout with a vertical orientation.  We then, in desired layout order, defined our title TextView, our description TextView, and our OK Button (footer).

The title TextView and OK Button both specify their heights to be "wrap_content".  This tells the views' parent to size them just tall enough to fit their content (their text + any padding).

The description TextView specifies its height to be "fill_parent" (replaced with "match_parent" in later versions of Android OS).  This tells the view's parent to fill in any remaining space that the parent may have with the TextView.

So, we would expect to see our title text at the top of the screen, our OK button at the bottom of the screen, and our description politely occupying the area in the middle.  No such luck.  If you were to try the above, you would see that our title does indeed appear at the top of our view.  However, our description occupies the rest of the screen, pushing the OK button off into the ether.

Enter the rabbit hole.

It turns out, if we simply add a layout_weight other than 0 to our description text view, everything falls neatly into place.  Our updated text view looks like:

  <TextView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="Some description of our content" />

No comments:

Post a Comment