Android Gravity

What is the difference between android:gravity and android:layout_gravity? Explain with example.

The main difference between android: gravity and android: layout_gravity are as follows.
  • android: gravity: sets the position of the content of the View i.e. what contents are inside the view.
  • If you want that text (Caption) of Button control to be left aligned, center, or right aligned, then modify the gravity attribute of the Button control.
  • android:layout_gravity: sets the position of the View with respect to its parent.
  • It simply controls that where your view will place inside the parent.
  • Suppose that you have a Button control inside a linear layout, and then setting the layout_gravity of the Button control will change its alignment in the layout.
  • Attribute gravity sets the alignment of the content of the view (Suppose Button). If you want your text to be left aligned, center, or right aligned, then modify the gravity attribute of the text view.
Example:

Following will be the content of res/layout/content_main.xml file:
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayoutxmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
app:layout_behavior = "@string/appbar_scrolling_view_behavior"
tools:context = "com.example.custom.and gravity.MainActivity"
tools:showIn = "@layout/activity_main"
android:orientation = "vertical"
>

<Button
android:layout_width = "130dp"
android:layout_height = "130dp"
android:text = "Button1"
android:id = "@+id/button1"
android:gravity = "top"
android:textSize = "20dp"
android:background = "#FF0000"
/>

<Button
android:layout_width = "130dp"
android:layout_height = "130dp"
android:text = "Button2"
android:id = "@+id/button2"
android:gravity = "bottom"
android:textSize = "20dp"
android:background = "#00FF00"
/>

<Button
android:layout_width = "130dp"
android:layout_height = "130dp"
android:text = "Button3"
android:id = "@+id/button3"
android:textSize = "20dp"
android:layout_gravity = "right"
android:gravity = "top"
android:background = "#FFFF00"
/>
</LinearLayout>

The output of the above given code will be as follows:

Android gravity