问题
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.
回答1:
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();
}
回答2:
Use R.attr.
setTextColor(android.R.attr.editTextColor)
回答3:
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.
来源:https://stackoverflow.com/questions/8598414/get-an-edittexts-default-color-value-from-theme