Set border color of EditText in android programmatically

How to create custom EditText with border dynamically using setBackgroundResource.

In this tutorial we are creating an extra edittext_border.xml file with border tags. Now we are setting up this layout file as EditText background via programmatically method from MainActivity.java programming file using setBackgroundResource() method. So here is the complete step by step tutorial for Set border color of EditText in android programmatically.

android-project-download-code-button

Note: create edittext_border.xml file inside layout folder.

layout-folder

How to Set border color of EditText in android programmatically.

Code for MainActivity.java file.

 package com.edittextwithborderprogrammatically_android_examples.com;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;

public class MainActivity extends Activity {

 EditText editText;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 editText = (EditText)findViewById(R.id.editText1);
 
 //Setting up border xml file dynamically.
 editText.setBackgroundResource(R.layout.edittext_border);
 
 }
}

Code for activity_main.xml layout file.

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.edittextwithborderprogrammatically_android_examples.com.MainActivity" >

 <EditText
 android:id="@+id/editText1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:ems="10"
 android:hint="EditText" >

 </EditText>
 
</RelativeLayout>

Code for edittext_border.xml file.

 <selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
 <shape android:shape="rectangle">
 <solid android:color="#ffffff"/>
 <stroke
 android:width="1dp"
 android:color="#fa3b5a"
 />
 </shape>
</item>
</selector>

Screenshot:

Set border color of EditText in android programmatically

Click here to download Set border color of EditText in android programmatically project with source code.

Leave a Reply

Your email address will not be published. Required fields are marked *