What is the difference between gravity and layout_gravity in Android?

前端 未结 20 1157
庸人自扰
庸人自扰 2020-11-21 11:41

I know we can set the following values to the android:gravity and android:layout_gravity properties:

    <
20条回答
  •  难免孤独
    2020-11-21 12:07

    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.

提交回复
热议问题