Sunday, November 21, 2010

Utilizing Android LinearLayout

I have been using the Android LinearLayout for a test application. There is some documentation and a minor preview of what it does, but I don't think this makes it simple to understand.
I tried searching for a better explanation, but none came up, so here is my version.

The xml that I'm using as a base is this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="100px" android:layout_height="80px"
    android:orientation="vertical"
    >
    
    <TextView 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent"
        android:layout_weight="1" 
        android:text="1"
        android:textColor="#000000"
        android:gravity="center" 
        android:background="#ff0000"
    />

    <TextView 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent"
        android:layout_weight="1" 
        android:text="1"
        android:textColor="#000000"
        android:gravity="center" 
        android:background="#00ff00"
    />

    <TextView 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent"
        android:layout_weight="1" 
        android:text="1" 
        android:textColor="#000000"
        android:gravity="center" 
        android:background="#0000ff"
    />
</LinearLayout>


When you set the layout_height to fill_parent and the layout_weight to the same number, the available space is divided between the elements. This makes it possible to have two or more elements sharing the available space, where each gets the same amount of space:

This was about what I could gather from the demo page. But what if you want a fixed size header, and have the two following elements share whatever space is left? The solution is to set the layout_height of the fixed-size element to wrap_content, and then set the layout_weight to 0 for that element:

This is counter-intuitive to me, because the name layout_weight is really a priority instead, so each item with the same layout_weight share the remaining space evenly. Once all elements with priority (layout_weight) 0 are placed, all elements with priority 1 then share the remaining layout space.

This lead me to investigate the reason for choosing the word weight, and it turns out that the value doubles as a weight as long as it is less than 1.0:

No comments: