Search code examples
androidandroid-edittextandroid-resourcesandroid-drawable

Programmatically Set Background Resource of EditText to transparent field


This is the default way an EditText looks when I create one:

This is what it looks like after I change the background of it:

enter image description here

To change the background to the image above, I add the following EditText property to my EditText in my XML file:

android:background="@android:drawable/edit_text"

What I want to do is do what I've done above in my activity class (giving the user an option to select between the classic style and the transparent/new style).

So like this - I need people to fill in the /*...*/

if (classicTextbox()) { // the blocky white one

    editText.setTextColor(Color.BLACK);
    editText.setBackgroundResource(android.R.drawable.edit_text);

} else { // the new transparent one

    editText.setTextColor(Color.WHITE);
    editText.setBackgroundResource(/*...*/);
}

So how do I change it back to the new, transparent EditText style?


Solution

  • I ended up trying to just save the original Drawable when the layout is opened and then set the background resource that way whenever I want. Like this:

    In my onCreate method:

    Drawable originalDrawable = editText.getBackground();
    

    And then to set it:

    // need to use .setBackground and .setBackgroundDrawable depending on the 
    // android version because .setBackgroundDrawable is depreciated
    int sdk = android.os.Build.VERSION.SDK_INT;
    int jellyBean = android.os.Build.VERSION_CODES.JELLY_BEAN;
    if(sdk < jellyBean) {
        editText.setBackgroundDrawable(originalDrawable);
    } else {
        editText.setBackground(originalDrawable);
    }
    

    I still encourage more answers because I don't quite like this solution.


    Sources:

    How to return to default style on EditText if I apply a background?

    setBackground vs setBackgroundDrawable (Android)