Wednesday, December 21, 2011

Android Layout 101

Sarah Allen invited me to teach Android classes at Blazing Cloud, and we kicked off last night with Android Layout 101.



Presenting: Android Layout 101

We started with the Hello World app, gradually introducing more and more layout types and attributes. From time to time I showed a screenshot and asked everyone to modify the xml file to achieve the same layout.



"hmm... how I do get the buttons to go to the second line?"

By the end of the workshop we were implementing this screen:

This can be done with either LinearLayout or RelativeLayout. The LinearLayout version uses a nested horizontal LinearLayout to specify the second row, with android:gravity="right" to scoot the buttons over. One of the students, Anne, went on to experiment with setting android:layout_gravity="right" on the buttons themselves, but that did not work. We were quite baffled.

Turns out android:layout_gravity="right" is only honored by a vertical LinearLayout, not horizontal one. I guess the LinearLayout expects to put down one View after another horizontally, so if it puts the first button to the right, the second button would have nowhere to go. As a result it simply ignores the layout_gravity attributes. Still, it was rather confusing, and it is precisely the kind of nuance you only find out when you get your hands dirty.

The screenshot exercises gave everyone a chance to put theory into practice, and see how the elements interact with each other. You can try them as well. Just go to http://www.sqisland.com/talks/android-layout-101. Even if you are already familiar with the basic layout components, you may still want to check out puzzles at the end. Some of the solutions may surprise you!

No comments:

Post a Comment

Inline coding questions will not be answsered. Instead, ask on StackOverflow and put the link in the comment.