Chapter 1. Working your way around layouts

 

In this chapter, we’ll cover tips and recommendations for Android layouts. You’ll learn how to create certain types of layouts from scratch as well as how to improve upon existing ones.

Hack 1 Centering views using weights: Android v1.6+

At an Android talk I gave to a group of developers, when I was explaining how to create a view using an XML file, someone asked, “What should I write if I want a button to be centered and 50% of its parent width?” At first I didn’t understand what he was asking, but after he drew it on the board, I understood. His idea is shown in figures 1.1 and 1.2.

Figure 1.1. Button with 50% of its parent width (portrait)
Figure 1.2. Button with 50% of its parent width (landscape)

It looks simple, right? Now take five minutes to try to achieve it. In this hack, we’ll look at how to solve this problem using the LinearLayout’s android:weightSum attribute in conjunction with the LinearLayout’s child android:layout_weight attribute. This might sound like a simple task, but it’s something I always ask about in interviews with developers because a lot of them don’t know the best way to do this.

1.1. Combining weightSum and layout_weight

Android devices have different sizes, and as developers we need to create XML in a way that works for different screen sizes. Hard-coding sizes isn’t an option, so we’ll need something else to organize our views.

Hack 2 Using lazy loading and avoiding replication: Android v1.6+

Hack 3 Creating a custom ViewGroup: Android v1.6+

Hack 4 Preferences hacks: Android v1.6+