code snippets, examples, and tricks for software developers
Saturday, May 21, 2011
Stretching Rows in Android TableLayout
Google's Android SDK allows developers to architect a UI from the comfort and safety of XML. This is done by creating a layout resource *.xml file under the /res/layout directory of the project.
Hand-coded UIs can be difficult to maintain and update. For example, grid-based layouts can become complex and unwieldy as they evolve. An XML-based layout tries to address these problems, and the Android Developers forum provides helpful tutorials on the subject.
As I studied the layout tutorials, I hoped to use percentage values for the android:layout_height and android:layout_width attributes to evenly stretch buttons in a TableLayout. Since percentage values are not allowed however, another solution was required.
The android:stretchColumns attribute addresses part of the problem. For example, a 3-column table layout can be evenly laid out--horizontally, at least--by setting android:stretchColumns="0,1,2". But the rows are not stretched and no corresponding android:stretchRows exists.
The solution actually depends android:stretchColumns as well as a few other layout attributes and can be outlined as follows:
give the top-level TableLayout node in the XML file an android:weightSum value corresponding to the number of rows in the layout. If the layout has 3 rows, then set android:weightSum=3.
give each TableRow node within the TableLayout an android:layout_weight attribute and set the value such that the sum of all the android:layout_weight values from all the nodes within is equal to the value of android:weightSum in the containing TableLayout.
set the android:layout_height and android:layout_width of the items inside the TableRow elements ( in my case, a Button element ), to "fill_parent."
With this approach, I was able to achieve the above pictured layout without hard-coding any numeric values in the XML for height or width. Here is the XML that I used as a layout resource in my test Android app:
4 comments:
Good job :)
Could you check your code please? It looks like crap and doesn't work.
Thanks for the nice tutorial man... Even this
http://www.compiletimeerror.com/2013/07/android-tablelayout-example.html might help, have a look..
Nice job. You need to change wrap_content to match_parent in order to resize buttons.
Post a Comment