How can I center these buttons on Android?
The code I'm using in the layout
is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<Button android:text="Test"
android:layout_width="100px"
android:layout_height="40px" />
<Button android:text="Test"
android:layout_width="100px"
android:layout_height="40px" />
<Button android:text="Test"
android:layout_width="100px"
android:layout_height="40px" />
<Button android:text="Test"
android:layout_width="100px"
android:layout_height="40px" />
</LinearLayout>
</LinearLayout>
android:gravity="center" for text center in TextView. android:gravity="center_horizontal" inner text if you want horizontally centered. android:gravity="center_vertical" inner text if you want vertically centered. android:layout_centerInParent="true" if you want TextView in center position of parent view.
Below that, the layout_height=0 and layout_weight=1 attributes on the RelativeLayout cause it to take up all the remaining space. You can then center the button in the RelativeLayout . You can play with padding on the button to get it to the size you want.
Make the LinearLayout containing the buttons to wrap_content on width and to have center_horizontal on gravity.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<LinearLayout android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:layout_gravity="center_horizontal">
<Button android:text="Test"
android:layout_width="100px"
android:layout_height="40px" />
<Button android:text="Test"
android:layout_width="100px"
android:layout_height="40px" />
<Button android:text="Test"
android:layout_width="100px"
android:layout_height="40px" />
<Button android:text="Test"
android:layout_width="100px"
android:layout_height="40px" />
</LinearLayout>
</LinearLayout>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With