Tuesday, August 18, 2015

How to change EditText border color in Android

Change EditText Border Color
EditText is an android user interface element that allows app users to enter text and also modifying text. Sometimes android app developers want to modify the default border color of the EditText widget.

This tutorial demonstrates, how can we change the EditText input widget’s border color in our android application. To do this, at first we will create an activity layout file. In this XML layout file, we will put an EditText widget on it.

EditText widget has a property/attribute named background. We have to put a value here to change the EditText various colors, such as background color and border color. The EditText background attribute value point to an XML drawable file that holds the actual color definitions.

In the second step, we will create an XML drawable file to apply custom colors to the EditText widget. XML drawable file has a selector and an item tag. This file defines the EditText shape also.

Inside the shape tag we will put two more elements one for describing EditText background color and another one for defining EditText border color and border width/thickness. When we will render the app, this drawable specified border color will show on 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="#b6ca9f"
    >
    <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"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@android:color/transparent"/>
            <stroke android:width="1dp" android:color="#a17dff"/>
        </shape>
    </item>
</selector>