How gravity
affects
the subviews is shown in the image below.
I resized the widths of all the subviews so that what is happening is more clear.
Note that
the way RelativeLayout
handles
gravity is to take all the subviews as a group and move them around the layout. This means that whichever
view is widest will determine how everything else is positioned. So gravity in a Relative layout is probably only useful if all the subviews have the same width.
Linear Layout with gravity
When you add gravity
to
a LinearLayout
,
it does arrange the subviews as one would expect.
For example, one could "save code" by setting the gravity
of LinearLayout
to center_horizontally
.
That way there is no need individually set the layout_gravity
of
each subview. See the various options in the image below.
Note that when a view uses layout_gravity
,
it overrides the LinearLayout's gravity. (This can be seen in the title for the two layouts in the left image. The LinearLayout gravity
was
set to left
and right
,
but the title TextView's layout_gravity
was
set to center_horizontally
.)
Final notes
When positioning views within a RelativeLayout, the general way to do it is adding things like the following to each view:
layout_alignParentTop
layout_centerVertical
layout_below
layout_toRightOf
If one wants to set all the views at once, a LinearLayout
would
likely be better (or perhaps using a Style).
So to sum up,
- The
layout_gravity
does not work for subviews in a RelativeLayout. - The
gravity
of a RelativeLayout does work, but not as one might expect.