Tuesday, August 18, 2015

How to change EditText bottom border color in Android

Change EditText Bottom Border Color
In an Android application, The EditText element is used for entering and modifying text. Android SDK provides a default look for the EditText widget. But, sometimes developers need to change the default color and shape of the EditText widget.

This android app development tutorial demonstrates to us how can we change the EditText widget’s bottom border color and bottom border thickness.

In the first step, we have to create an XML layout file to put an EditText. Next step, we will put our code to modify the EditText bottom border color. EditText has a property named background. We will put a value here that point to a drawable XML file.

This drawable XML file has the actual code to modify the EditText bottom border color and thickness. This drawable file holds a layer list. The layer list consists of two items, one item stay top on another item. The first item defines the border color and thickness of EditText and the second item draws a solid color on the EditText background.

The main logic is that in the second item we offset the background color 2 DP’s in the bottom, so it draws a 2 DP’s width border at the bottom of the EditText element. As a result, we get our specified colored and thickness bottom border of the EditText.
activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#c9cac1"
    >
    <EditText
        android:id="@+id/et"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="Input your country"
        android:background="@drawable/edittext_bg"
        android:padding="10dp"
        />
</RelativeLayout>
res/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">
            <!-- Draw a 2dp width border around shape -->
            <stroke
                android:color="#ff1e0c"
                android:width="2dp"
                />
        </shape>
    </item>
    <!-- Overlap the left, top and right border using background color  -->
    <item
        android:bottom="2dp"
        >
        <shape android:shape="rectangle">
            <solid android:color="#fffbce"/>
        </shape>
    </item>
</layer-list>