Need help centering an EditText in a Linear Layout

codesomethin picture codesomethin · Jan 24, 2012 · Viewed 9k times · Source

I'm trying to center an edittext vertically and horizontally in a linear layout, but it is not working. Very simple problem really.

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" 
 android:background="@drawable/login">



<EditText
    android:layout_width="150dp"
    android:layout_height="wrap_content"
    android:background="@drawable/loginbutton"
    android:text="Username"
    android:layout_gravity="center"
    android:textSize="25dp"
    android:gravity="center_horizontal|center_vertical"
    android:textColor="#000000"
    android:layout_margin="10dp"
    android:id="@+id/username">
  </EditText>

I'll try changing to a relativelayout in the mean time.

Answer

Jave picture Jave · Jan 24, 2012

LinearLayout do not support centering in the direction it stacks items as far as I know. Unless the LinearLayout is crucial (which in your case it shouldn't be, as you also need the centering), I would recommend you switch to a RelativeLayout.
With a RelativeLayout, you can set the attribute android:layout_centerInParent="true" on the EditText to get it centred.