34

I just encountered with a problem that I don't know how to solve. It looks silly but I cannot find a way to fix it.

I have a form in android with several EditText and when you submit the form it checks those EditText and if they have wrong data I change the EditText to red border (applying a ninepatch image).

myEditText.setBackgroundResource(R.drawable.edittext_red);

The problem is, I want to restore android's default style when the user change the EditText, but I don't know how to do it. if I do:

myEditText.setBackgroundResource(0);

It will just remove everything and that's not what I want.

Thanks!

Marmoy
  • 7,684
  • 7
  • 41
  • 72
SERPRO
  • 9,674
  • 7
  • 40
  • 61

2 Answers2

63

First, before you call setBackgroundResource with your own ninepatch, store the original background of the EditText, like this:

Drawable originalDrawable = myEditText.getBackground();

Then, if the user entered the wrong data, you can set your red border ninepatch:

myEditText.setBackgroundResource(R.drawable.edittext_red);

And later, when you want to restore the look of the EditText, use the stored drawable:

myEditText.setBackgroundDrawable(originalDrawable);

Alternatively you can reference the default Android EditText background directly like this:

myEditText.setBackgroundResource(android.R.drawable.edit_text);

At androiddrawables you can see how the different drawables look for the different versions of Android, and get their resource identifier. This method should work for all drawables, not just EditText

These (and other android resources) can also be found on your own system, in the android-sdk folder in

< path to android-sdk folder>/android-sdk/platforms/android-< API level>/data/res/

Marmoy
  • 7,684
  • 7
  • 41
  • 72
  • Hey SeRPRo- you ought to mark videre's answer as correct, it will give you both points and inform future users that this was the solution. – Nathan Fig Aug 02 '11 at 13:03
  • 7
    Your alternative solution was THE answer that I was looking for. It was the simplest and easiest way of restoring the original look of your EditText (even restores the size as well!). But instead of using editbox_background_normal I just used android.R.drawable.edit_text – faul Dec 28 '11 at 22:11
  • 5
    When doing this on ICS, it seems a old 2.3 style will be applied. Did you notice this too? – Sebastian Roth May 01 '12 at 09:28
  • @faul 's comment should be the answer! +1 although original answer is better explained :) +1 – beerBear Jan 28 '15 at 16:11
2

For material design with Kotlin:

edit.apply {
    setBackgroundResource(androidx.appcompat.R.drawable.abc_edit_text_material)
}