Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 334
Unpossible Avatar asked Dec 22 '11 01:12

Unpossible


2 Answers

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.

like image 159
Charles Harley Avatar answered Oct 25 '22 04:10

Charles Harley


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();
}
like image 35
Diederik Avatar answered Oct 25 '22 05:10

Diederik