Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help centering an EditText in a Linear Layout

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.

like image 384
codesomethin Avatar asked Jan 24 '12 15:01

codesomethin


People also ask

How do you center text in linear layout?

If in linearlayout your orientation vertical, you can put the textview in the "horizontal center" by android:layout_gravity="center" . For centering textview vertically you need to set layout_height of textview to match_parent and set android:gravity to "center".

How do you center EditText?

Simpler Solution to align text in EditText is to add android:gravity="center" in layout xml. There is no need to add Java code.

What's the difference between LinearLayout and RelativeLayout?

Android Layout Types Android provides the following ViewGroups or layouts: LinearLayout : is a ViewGroup that aligns all children in a single direction, vertically or horizontally. RelativeLayout : is a ViewGroup that displays child views in relative positions.

How do I center a button in layout?

If you have a single Button in your Activity and you want to center it the simplest way is to use a RelativeLayout and set the android:layout_centerInParent=”true” property on the Button.


1 Answers

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.

like image 115
Jave Avatar answered Sep 21 '22 03:09

Jave