Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Short Answer: use <code>android:gravity</code> or <code>setGravity()</code> to control gravity of all child views of a container; use <code>android:layout_gravity</code> or <code>setLayoutParams()</code> to control gravity of an individual view in a container.</p> <p>Long story: to control gravity in a linear layout container such as <code>LinearLayout</code> or <code>RadioGroup</code>, there are two approaches:</p> <p>1) To control the gravity of ALL child views of a <code>LinearLayout</code> container (as you did in your book), use <code>android:gravity</code> (not <code>android:layout_gravity</code>) in layout XML file or <code>setGravity()</code> method in code.</p> <p>2) To control the gravity of a child view in its container, use <code>android:layout_gravity</code> XML attribute. In code, one needs to get the <code>LinearLayout.LayoutParams</code> of the view and set its gravity. Here is a code example that set a button to bottom in a horizontally oriented container:</p> <pre><code>import android.widget.LinearLayout.LayoutParams; import android.view.Gravity; ... Button button = (Button) findViewById(R.id.MyButtonId); // need to cast to LinearLayout.LayoutParams to access the gravity field LayoutParams params = (LayoutParams)button.getLayoutParams(); params.gravity = Gravity.BOTTOM; button.setLayoutParams(params); </code></pre> <p>For horizontal <code>LinearLayout</code> container, the horizontal gravity of its child view is left-aligned one after another and cannot be changed. Setting <code>android:layout_gravity</code> to <code>center_horizontal</code> has no effect. The default vertical gravity is center (or center_vertical) and can be changed to top or bottom. Actually the default <code>layout_gravity</code> value is <code>-1</code> but Android put it center vertically. </p> <p>To change the horizontal positions of child views in a horizontal linear container, one can use <code>layout_weight</code>, margin and padding of the child view. </p> <p>Similarly, for vertical View Group container, the vertical gravity of its child view is top-aligned one below another and cannot be changed. The default horizontal gravity is center (or <code>center_horizontal</code>) and can be changed to left or right.</p> <p>Actually, a child view such as a button also has <code>android:gravity</code> XML attribute and the <code>setGravity()</code> method to control its child views -- the text in it. The <code>Button.setGravity(int)</code> is linked to this <a href="http://developer.android.com/reference/android/widget/TextView.html#setGravity%28int%29">developer.android.com entry</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload