Ajinkya
Ajinkya

Reputation: 22710

How to bring button to center of the screen in Android

I have a single button in Linear layout and I want to keep it at the center (horizontally).
I set android:gravity="center_horizontal" for button and linear layout but no luck.

 <LinearLayout android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/linearLayout4" android:layout_gravity="center_horizontal">
        <Button android:id="@+id/button1" android:layout_height="wrap_content" android:layout_width="wrap_content" android:gravity="center_horizontal" android:text="Search"></Button>
    </LinearLayout>

Sorry for such a basic question but as far as I know only android:gravity can be used to bring it to center and it didn't work for me.

Solution:

Thanks to Sbossb

<RelativeLayout android:id="@+id/RelativeLayout01"
        android:layout_width="fill_parent" android:layout_height="wrap_content">
        <Button android:id="@+id/Button01" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:text="Search"
            android:layout_centerInParent="true"></Button>
    </RelativeLayout>

~Ajinkya.

Upvotes: 6

Views: 37102

Answers (4)

SERPRO
SERPRO

Reputation: 10067

You can use the solution in this question: Center a button in a Linear layout

Basically, instead of LinearLayout, use RelativeLayout.

Upvotes: -1

C--
C--

Reputation: 16558

Try using this layout!

<LinearLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal">
    <LinearLayout android:id="@+id/linearLayout2" android:layout_height="wrap_content" android:gravity="center" android:layout_width="match_parent">
        <Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
    </LinearLayout>
</LinearLayout>

Upvotes: 5

Stefan Bossbaly
Stefan Bossbaly

Reputation: 6794

You could use a relative layout and set the child to android:layout_centerInParent="true". LinearLayout are a little tricky when it comes to centering check out this article http://sandipchitale.blogspot.com/2010/05/linearlayout-gravity-and-layoutgravity.html.

Upvotes: 11

JDx
JDx

Reputation: 2655

It should be android:layout_gravity instead of android:gravity.

Upvotes: 4

Related Questions