Center layout Android

ingh.am picture ingh.am · Nov 25, 2010 · Viewed 23.9k times · Source

How can I center these buttons on Android? alt text

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>

Answer

aromero picture aromero · Nov 25, 2010

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>