2

I am really a new fresher in android, I know android:layout_gravity sets the gravity of the View or Layout in its parent.And android:gravity sets the gravity of the content of the View its used on.Refer

But when I set the titlebar Linearlayout gravity="center",the button did sit in the center

But when I delete gravity="center" in the head of LinerLayout,then add layout_gravity="center" in the button,the button sit in the left?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <Button
        android:id="@+id/back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Back"
        android:layout_gravity="center"
        android:textColor="#fff" />

</LinearLayout>

enter image description here

Community
  • 1
  • 1
Gaby
  • 130
  • 1
  • 8

4 Answers4

3

just give orientation to your LinearLayout, rest all things are perfect

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <Button
    android:id="@+id/back"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Back"
    android:layout_gravity="center"
    android:textColor="#fff" />

</LinearLayout>
Ravi
  • 34,851
  • 21
  • 122
  • 183
  • Yeah! Is that means `layout_gravity` must work with `LinearLayout orientation` ? If I add two other widget `TextView` and `Button`, – Gaby Dec 11 '15 at 05:48
2

check the following code and button at center:

 <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical">
          <Button
              android:layout_width="100dp"
              android:layout_height="100dp"
              android:layout_gravity="center"/>
     </LinearLayout>
Abhinav Singh Maurya
  • 3,313
  • 8
  • 33
  • 51
Prathap Badavath
  • 1,621
  • 2
  • 20
  • 24
0
   <?xml version="1.0" encoding="utf-8"?>
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="wrap_content"
   >

<Button
    android:id="@+id/back"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Back"
    android:textColor="#fff" />

Deepanker Chaudhary
  • 1,694
  • 3
  • 15
  • 35
0

add android:orientation="vertical" in the LinearLayout

Halgo
  • 13
  • 5