When you’re designing your application, you might have com-
plex views that will show up in different activities. Imagine that
you’re creating a card game and you want to show the user’s
hand in a layout similar to figure 3.1. How would you create a
layout like that?
You might say that playing with margins will be enough for
that type of layout. That’s true. You can do something similar
to the previous figure with a RelativeLayout and add margins
to its children. The XML looks like the following:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<View
android:layout_width="100dp"
android:layout_height="150dp"
android:background="#FF0000" />
<View
android:layout_width="100dp"
android:layout_height="150dp"
android:layout_marginLeft="30dp"
android:layout_marginTop="20dp"
android:background="#00FF00" />
<View
android:layout_width="100dp"
android:layout_height="150dp"
android:layout_marginLeft="60dp"
android:layout_marginTop="40dp"
android:background="#0000FF" />
</RelativeLayout>
</FrameLayout>
The result of the previous XML can be seen in
figure 3.2.
In this hack, we’ll look at another way of creating
the same type of layout—we’ll create a custom View-
Group. The benefits of using a custom ViewGroup
instead of adding margins by hand in an XML file are
these:
It’s easier to maintain if you’re using it in differ-
ent activities.
Figure 3.1 User’s
hand in a card game
Figure 3.2 Card layout created
using the default Android widgets
You can use custom attributes to customize the position of the ViewGroup chil-
dren.
The XML will be easier to understand because it’ll be more concise.
If you need to change the margins, you won’t need to recalculate by hand every
child’s margin.
Let’s take a look at how Android draws views.