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
gravityof aLinearLayoutitself changes the location of the views within it. Setting the layout_gravity of aLinearLayoutchanges how theLinearLayoutis arranged within its parent layout.This image shows a
LinearLayout(brown) within aFrameLayout(white). TheLinearLayout'sgravityis set tocenter_horizontaland itslayout_gravityis set toright|bottom.Here is the xml:
Changing things programmatically
The following code shows how to change both the
gravityand thelayout_gravityof theLinearLayout.And here is the result:
See also
RelativeLayoutandLinearLayoutwith gravity: What is the effect?