Home > Mobile >  Custom drawable background for Android EditText
Custom drawable background for Android EditText

Time:04-17

I would like to create a custom drawable background for an EditText component in my Android layout. This should include a lower border spanning the entire length of the EditText, and 2 connected vertical lines at either end which take up 25% of the height, as per below:

EditText with custom border

The text itself will then use android:gravity="left|center" with a small amount of margin on the left/top/bottom.

I've been able to create a custom border on other input text elements where it was desirable to include all borders using a shape such as below:

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

    <corners
        android:bottomRightRadius="4dp"
        android:bottomLeftRadius="4dp"
        android:topLeftRadius="4dp"
        android:topRightRadius="4dp"/>
    <stroke
        android:color="@color/lightgrey"
        android:width="1dp"/>
</shape>

However, now I don't want a full rectangle, only 1 full side 2 partial sides.

CodePudding user response:

Two steps to achieve that:

  • Keep only the bottom border by removing the top, right, and left borders by adding negative insets with android:left|right|top.
  • Add new rectangle for the side items: adjust left/right relevant gravity, and limit the height to which size you want (here it's set to 8dp):
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <!--    Bottom border -->
    <item
        android:left="-50dp"
        android:right="-50dp"
        android:top="-50dp">
        <shape android:shape="rectangle">
            <stroke
                android:width="1dp"
                android:color="@color/lightgrey" />
        </shape>

    </item>

    <!--    Left border -->
    <item
        android:height="8dp"
        android:gravity="left|bottom">
        <shape android:shape="rectangle">
            <solid android:color="@color/lightgrey" />
            <size android:width="1dp" />
        </shape>
    </item>

    <!--    Right border -->
    <item
        android:height="8dp"
        android:gravity="right|bottom">
        <shape android:shape="rectangle">
            <solid android:color="@color/lightgrey" />
            <size android:width="1dp" />
        </shape>
    </item>

</layer-list>

Here is the result

enter image description here

  • Related