Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align TextView and EditText left in vertically oriented LinearLayout

I am using a LinearLayout as view group which holds two children (TextView and EditText). My XML code looks as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Text View"
        android:textSize="20sp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="Edit Text"
        android:textSize="20sp" />

</LinearLayout>

which will produce the following design:

enter image description here

As depicted in the zoomed-in view on the left, TextViewand EditText are not equally aligned vertically (EditText is indented a bit more as shown by the small red arrows).

It seems there is a bit of a padding (a few dp) around the hint and the line underneath which prevents them from "touching" the left edge of their view field. Is there any way to force the hint within EditText to squeeze to the left of its view field?

How can I get rid of this indentation, other than by adding paddings and margins?

Thanks for any ideas and advice!

like image 482
Jonathan Rhein Avatar asked May 22 '26 04:05

Jonathan Rhein


1 Answers

Without add any paddings and margins you can use a custom drawable for the background of your Edittext to remove the default padding

in drawable/edittext_bg.xml

 <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@android:color/transparent" />
        </shape>
    </item>

    <item
        android:top="-2dp"
        android:right="-2dp"
        android:left="-2dp">
        <shape>
            <solid android:color="@android:color/transparent" />
            <stroke
                android:width="1dp"
                android:color="#000000" />
        </shape>
    </item>
</layer-list>

Now use it in your editext:

<EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/edittext_bg"
        android:hint="Edit Text"
        android:textSize="20sp" />

Output:

enter image description here

like image 189
rafsanahmad007 Avatar answered May 24 '26 16:05

rafsanahmad007



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!