Wednesday, 21 September 2011

Android: displaying widgets in a grid-like layout

(UPDATE)
Now that Ice Cream sandwich is here, we also can user the new GridLayout. I'll write about it as soon as I have time.

It sounds simple but I get this question all the time: How do I make TextView, EditText, Buttons, and such to be evenly distributed in a grid like layout?

There are many ways to do that (I think) but the simplest one is using a standard LinearLayout with android:orientation="horizontal", adjusting the property layout_weight of each widget inside the layout.

If we create a layout like this


<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cras in eros nunc"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="non viverra justo"/>
</LinearLayout>


we'll get this

which one could say doesn't look very good.
But if we add android:layout_weight="1" to each of the text views, like 

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Cras in eros nunc"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="non viverra justo"/>
</LinearLayout>


the 2 text views will use respectively 50% of the width of the parent, looking like this

 android:layout_weight basically set how much of the usable area a widget can use. It accepts floating numbers so we can do things like this:

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.1"
android:background="#ff0000"
android:text="Cras in eros nunc"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.9"
android:background="#0000ff"
android:text="non viverra justo"/>
</LinearLayout>




and get this

note that I changed the background colour just to make the difference more visible.

As I mentioned, the weight is applied to the available area inside the parent and in the examples above, the parent has android:layout_width="fill_parent". If we change it to android:layout_width="wrap_content" this happens.


So be aware of your surroundings!

Next post I'll talk about TableLayouts and TableRows.

Have a good one!