When I was first starting to develop Android applications, I frequently ran into a scenario that quite frankly some days left me wondering if I wouldn’t prefer a root canal to hitting the CMD-F11 key one more time. (If you’re not a user of Eclipse on a Mac, CMD-F11 is the run key.) The cause of my misery had to do with Android layouts — specifically the TableLayout.

You see, while table layouts are well suited for certain types of application screens, the Android implementation always seemed to leave me banging my head against my monitor. At times the most straightforward of layouts refused to flow correctly, and in the end I would often give up on the table layout all together and switch to some form of nested linear layouts.

In most cases, I wanted my table to grow to fill the entire width of the screen, and I wanted the cells with a table row to expand, evenly or to a specific ratio of the entire table width. It always seemed to me that using wrap content or fill parent, in conjunction with some layout weight, would give me the control I wanted. Alas, it never did.

After more hours than I care to count, I finally came across the painfully simple answer: The width of each cell had to be set to “0dp.” Eventually it became second nature to me, and I almost managed to forget about all the headaches that elusive setting cost me when I was an Android noob. Then recently I was asked by an intern to take a look at a table view that “wasn’t acting right.”

So for all those developers who are just starting on Android (or for those who simply stopped using TableLayout due to frustration), the quick tutorial below goes out to you. Feel free to follow along, or download and import the entire project directly into Eclipse.

1. Start a new Android project in Eclipse. Target SDK 14 (ICS) or better.

2. In the /res/layout folder create a table layout in activity_main.xml. The table contains a single row, with a weight sum of 1, and 3 cells, each with a weight that matches the corresponding text. The most important thing is the layout width parameter of the table cells MUST be set to 0dp.


That’s it. Since we aren’t doing anything with the tables, we can run the APK on a device or an emulator with the generated Java code to see the layout in action (Figure A).

Figure A

Nothing to it — once you know how.