Wednesday, 14 November 2018

What is the difference between gravity and layout_gravity in Android?

Short Answer: use android:gravity or setGravity() to control gravity of all child views of a container; use android:layout_gravity or setLayoutParams() to control gravity of an individual view in a container.


Long story: to control gravity in a linear layout container such as LinearLayout or RadioGroup, there are two approaches:


1) To control the gravity of ALL child views of a LinearLayout container (as you did in your book), use android:gravity (not android:layout_gravity) in layout XML file or setGravity() method in code.


2) To control the gravity of a child view in its container, use android:layout_gravity XML attribute. In code, one needs to get the LinearLayout.LayoutParams of the view and set its gravity. Here is a code example that set a button to bottom in a horizontally oriented container:


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);

For horizontal LinearLayout container, the horizontal gravity of its child view is left-aligned one after another and cannot be changed. Setting android:layout_gravity to center_horizontal has no effect. The default vertical gravity is center (or center_vertical) and can be changed to top or bottom. Actually the default layout_gravity value is -1 but Android put it center vertically.


To change the horizontal positions of child views in a horizontal linear container, one can use layout_weight, margin and padding of the child view.


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 center_horizontal) and can be changed to left or right.


Actually, a child view such as a button also has android:gravity XML attribute and the setGravity() method to control its child views -- the text in it. The Button.setGravity(int) is linked to this developer.android.com entry.

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...