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.
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".
Simpler Solution to align text in EditText is to add android:gravity="center" in layout xml. There is no need to add Java code.
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.
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.
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.
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