[android] Change background color of edittext in android

If I change the background color of my EditText using the below code, it looks like the box is shrunken and it doesn't maintain the ICS theme of a blue bottom border that exists for a default EditText.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#99000000"
    >
    <EditText
        android:id="@+id/id_nick_name"
        android:layout_marginTop="80dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff"  
    />
    <LinearLayout 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
             android:layout_marginTop="10dip"
             android:layout_marginLeft="20dip"
             android:layout_marginRight="20dip"
            android:orientation="horizontal"
            android:layout_below="@+id/id_nick_name">  
        <Button 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="add"
            android:layout_weight="1"
            />
         <Button 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="cancel"
            android:layout_weight="1"
            />
    </LinearLayout>
</RelativeLayout>

Here is what it looks like:

Image of EditText

This question is related to android android-layout android-edittext

The answer is


For me this code it work So put this code in XML file rounded_edit_text

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item> <shape android:shape="rectangle"> <stroke android:width="1dp" android:color="#3498db" /> <solid android:color="#00FFFFFF" /> <padding android:left="5dp" android:top="5dp" android:right="5dp" android:bottom="5dp" > </padding> </shape> </item> </layer-list>


I worked out a working solution to this problem after 2 days of struggle, below solution is perfect for them who want to change few edit text only, change/toggle color through java code, and want to overcome the problems of different behavior on OS versions due to use setColorFilter() method.

    import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatDrawableManager;
import android.support.v7.widget.AppCompatEditText;
import android.util.AttributeSet;
import com.newco.cooltv.R;

public class RqubeErrorEditText extends AppCompatEditText {

  private int errorUnderlineColor;
  private boolean isErrorStateEnabled;
  private boolean mHasReconstructedEditTextBackground;

  public RqubeErrorEditText(Context context) {
    super(context);
    initColors();
  }

  public RqubeErrorEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    initColors();
  }

  public RqubeErrorEditText(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initColors();
  }

  private void initColors() {
    errorUnderlineColor = R.color.et_error_color_rule;

  }

  public void setErrorColor() {
    ensureBackgroundDrawableStateWorkaround();
    getBackground().setColorFilter(AppCompatDrawableManager.getPorterDuffColorFilter(
        ContextCompat.getColor(getContext(), errorUnderlineColor), PorterDuff.Mode.SRC_IN));
  }

  private void ensureBackgroundDrawableStateWorkaround() {
    final Drawable bg = getBackground();
    if (bg == null) {
      return;
    }
    if (!mHasReconstructedEditTextBackground) {
      // This is gross. There is an issue in the platform which affects container Drawables
      // where the first drawable retrieved from resources will propogate any changes
      // (like color filter) to all instances from the cache. We'll try to workaround it...
      final Drawable newBg = bg.getConstantState().newDrawable();
      //if (bg instanceof DrawableContainer) {
      //  // If we have a Drawable container, we can try and set it's constant state via
      //  // reflection from the new Drawable
      //  mHasReconstructedEditTextBackground =
      //      DrawableUtils.setContainerConstantState(
      //          (DrawableContainer) bg, newBg.getConstantState());
      //}
      if (!mHasReconstructedEditTextBackground) {
        // If we reach here then we just need to set a brand new instance of the Drawable
        // as the background. This has the unfortunate side-effect of wiping out any
        // user set padding, but I'd hope that use of custom padding on an EditText
        // is limited.
        setBackgroundDrawable(newBg);
        mHasReconstructedEditTextBackground = true;
      }
    }
  }

  public boolean isErrorStateEnabled() {
    return isErrorStateEnabled;
  }

  public void setErrorState(boolean isErrorStateEnabled) {
    this.isErrorStateEnabled = isErrorStateEnabled;
    if (isErrorStateEnabled) {
      setErrorColor();
      invalidate();
    } else {
      getBackground().mutate().clearColorFilter();
      invalidate();
    }
  }
}

Uses in xml

<com.rqube.ui.widget.RqubeErrorEditText
            android:id="@+id/f_signup_et_referral_code"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_toEndOf="@+id/referral_iv"
            android:layout_toRightOf="@+id/referral_iv"
            android:ems="10"
            android:hint="@string/lbl_referral_code"
            android:imeOptions="actionNext"
            android:inputType="textEmailAddress"
            android:textSize="@dimen/text_size_sp_16"
            android:theme="@style/EditTextStyle"/>

Add lines in style

<style name="EditTextStyle" parent="android:Widget.EditText">
    <item name="android:textColor">@color/txt_color_change</item>
    <item name="android:textColorHint">@color/et_default_color_text</item>
    <item name="colorControlNormal">@color/et_default_color_rule</item>
    <item name="colorControlActivated">@color/et_engagged_color_rule</item>
  </style>

java code to toggle color

myRqubeEditText.setErrorState(true);
myRqubeEditText.setErrorState(false);

This is my working solution

View view = new View(getApplicationContext());
view.setBackgroundResource(R.color.background);
myEditText.setBackground(view.getBackground());

The color you are using is white "#ffffff" is white so try a different one change in the values if you want until you get your need from this link Color Codes and it should go fine


The simplest solution I have found is to change the background color programmatically. This does not require dealing with any 9-patch images:

((EditText) findViewById(R.id.id_nick_name)).getBackground()
    .setColorFilter(Color.<your-desi??red-color>, PorterDuff.Mode.MULTIPLY);

Source: another answer


You should use style instead of background color. Try searching holoeverywhere then I think this one will help you solve your problem

Using holoeverywhere

just change some of the 9patch resources to customize the edittext look and feel.


one line of lazy code:

mEditText.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP);

Here the best way

First : make new xml file in res/drawable name it rounded_edit_text then paste this:

<?xml version="1.0" encoding="utf-8"?>
<shape  xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle" android:padding="10dp">
    <solid android:color="#F9966B" />
    <corners
        android:bottomRightRadius="15dp"
        android:bottomLeftRadius="15dp"
        android:topLeftRadius="15dp"
        android:topRightRadius="15dp" />
</shape>

Second: in res/layout copy and past following code (code of EditText)

<EditText
    android:id="@+id/txtdoctor"
    android:layout_width="match_parent"
    android:layout_height="30dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:background="@drawable/rounded_edit_text"
    android:ems="10" >
    <requestFocus />
</EditText>

I create color.xml file, for naming my color name (black, white...)

 <?xml version="1.0" encoding="utf-8"?>
 <resources>
    <color name="white">#ffffff</color>
    <color name="black">#000000</color>
 </resources>

And in your EditText, set color

<EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="asdsadasdasd"
        android:textColor="@color/black"
        android:background="@color/white"
        />

or use style in you style.xml:

<style name="EditTextStyleWhite" parent="android:style/Widget.EditText">
    <item name="android:textColor">@color/black</item>
    <item name="android:background">@color/white</item>
</style>

and add ctreated style to EditText:

 <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="asdsadasdasd"
        style="@style/EditTextStyleWhite"
        />

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-layout

How to check if a key exists in Json Object and get its value How to center the elements in ConstraintLayout Android - how to make a scrollable constraintlayout? Add ripple effect to my button with button background color? This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint Is it possible to put a ConstraintLayout inside a ScrollView? Differences between ConstraintLayout and RelativeLayout How to remove title bar from the android activity? How to have EditText with border in Android Lollipop Android: ScrollView vs NestedScrollView

Examples related to android-edittext

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint Design Android EditText to show error message as described by google Change EditText hint color when using TextInputLayout How to change the floating label color of TextInputLayout The specified child already has a parent. You must call removeView() on the child's parent first (Android) Edittext change border color with shape.xml Changing EditText bottom line color with appcompat v7 Soft keyboard open and close listener in an activity in Android EditText underline below text property Custom designing EditText