What is the difference between gravity and layout_gravity in Android?

前端 未结 20 1550
庸人自扰
庸人自扰 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:16

    Gravity: Allow you move the content inside a container. (How sub-views will be placed).

    Important: (MOVE along X-axis or Y-axis within available space).

    Example: Let's say if you were to work with LinearLayout (Height: match_parent, Width: match_parent) as root level element, then you will have full frame space available; and the child views says 2 TextViews (Height: wrap_content, Width: wrap_content) inside the LinearLayout can be moved around along x/y axis using corresponding values for gravity on parent.

    Layout_Gravity: Allow you to override the parent gravity behavior ONLY along x-axis.

    Important: (MOVE[override] along X-axis within available space).

    Example: If you keep in mind the previous example, we know gravity enabled us to move along x/y axis, i.e; the place TextViews inside LinearLayout. Let's just say LinearLayout specifies gravity: center; meaning every TextView needs to be center both vertically and horizontally. Now if we want one of the TextView to go left/right, we can override the specified gravity behavior using layout_gravity on the TextView.

    Bonus: if you dig deeper, you will find out that text within the TextView act as sub-view; so if you apply the gravity on TextView, the text inside the TextView will move around. (the entire concept apply here too)

提交回复
热议问题