I am risking writing a duplicate question, but as I was researching the answer to another SO question, I realized that I couldn't find a simple question and answer that included setting both gravity and layout_gravity of a LinearLayout
. Also, I was confused as to the difference between them when talking about a ViewGroup
rather than just a view. I am answering my question below.
Here are some of the other questions I viewed:
- How to set gravity to layout programmatically?
- Set gravity for LinearLayout programmatically
- android - setting LayoutParams programmatically
- LayoutParams gravity not working
- layout_gravity in LinearLayout
- Problem with setLayoutParams method in android UI
- how to set setLayoutParams for linear layout elements
- Is it possible to change the layout width and height in Android at run time?
Short answer
Set gravity
Set layout gravity
Background
Previously, I have explained the difference between 'gravity' and `layout_gravity' for views within a layout.
Setting the
gravity
of aLinearLayout
itself changes the location of the views within it. Setting the layout_gravity of aLinearLayout
changes how theLinearLayout
is arranged within its parent layout.This image shows a
LinearLayout
(brown) within aFrameLayout
(white). TheLinearLayout
'sgravity
is set tocenter_horizontal
and itslayout_gravity
is set toright|bottom
.Here is the xml:
Changing things programmatically
The following code shows how to change both the
gravity
and thelayout_gravity
of theLinearLayout
.And here is the result:
See also
RelativeLayout
andLinearLayout
with gravity: What is the effect?