"Grid" layout in Android

You know how your mother (or, in this case, your front end developer friends/colleagues) always say “never use a table for formatting unless you’re really making a table”

That may be true for HTML. However, it doesn’t seem to hold when you’re working with Google’s Android.

You see, now that I have a shiny new Motorola Droid (see my previous post), I’m now working with Android in my spare time.

I was struggling with using Android’s UI XML to layout a simple login page. And I was going nuts.

I was trying to use A LinearLayout containing several RelativeLayouts, one for each row. “Row” should have been the clue.

After poking through the PragProg Hello, Android book for a bit, I found an example later in the book that used a TableLayout.

That was my aha moment.

TableLayout is pretty simple to use. It is designed to contain several TableRow (a ViewGroup child as are other *Layouts). A TableRow looks thus:

  android:padding="10dip" >
android:layoutheight="wrapcontent" android:text="@string/login" /> <EditText android:id="@+id/login_field" android:layoutwidth="fillparent" android:layoutheight="wrapcontent" android:lines="1" /> </TableRow> <TableRow android:layout_marginBottom="10dip"> <TextView android:id="@+id/password_label" android:layoutheight="wrapcontent" android:text="@string/password" /> <EditText android:id="@+id/password_field" android:layoutwidth="fillparent" android:layoutheight="wrapcontent" android:lines="1" /> </TableRow>

The android:layout_marginBottom attributes on the TableRows are entirely optional. However, odds are that you will want to add some sort of formatting to your TableRows.

Incidentally, there may be DRYer ways of representing rows in Android XML (i.e., something similar to a Rails partial); however, admittedly, I’m still very much learning Android.

Posted by evan on Saturday, November 28, 2009

blog comments powered by Disqus