androidandroid-layoutlayout-gravity

android:layout_gravity="center" can't set the button in the center of titlebar?


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


Solution

  • 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>