Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 488
Ajinkya Avatar asked Jun 21 '11 15:06

Ajinkya


1 Answers

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.

like image 93
Stefan Bossbaly Avatar answered Oct 21 '22 03:10

Stefan Bossbaly