Home » Android » android – Get an EditText's 'default' color value from theme

android – Get an EditText's 'default' color value from theme

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have an Activity that contains an EditText on 3.1. Based on user input, I change the color of the text in the EditText (red for an error), and then reset it to black when the text is OK.

One issue relates to changing the overall theme of the Activity. For instance, changing it to the regular dark theme from the light theme results in the black text being shown against a black background – so I need to go in and change the code, instead resetting the text to white when the data is OK.

Instead of having to change this code if I make a theme change to the Activity, I was wondering if there was a way to pull the default EditText text color for a given theme programmatically, then I can just switch the text back to the default color instead of hard-coding in the white, black, etc.

How to&Answers:

According to the Theme’s docs get the colour directly using obtainStyledAttributes.

TypedArray themeArray = context.getTheme().obtainStyledAttributes(new int[] {android.R.attr.editTextColor});
try {
    int index = 0;
    int defaultColourValue = 0;
    int editTextColour = themeArray.getColor(index, defaultColourValue);
}
finally
{
    // Calling recycle() is important. Especially if you use alot of TypedArrays
    // http://stackoverflow.com/a/13805641/8524
    themeArray.recycle();
}

Answer:

Use R.attr.

setTextColor(android.R.attr.editTextColor)

Answer:

EditText.getCurrentTextColor() and EditText.getTextColors() will also provide the default colour if you retrieve them before changing the colour. Additionally this approach can be used pre 3.0 which is not possible when using android.R.attr.editTextColor.