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

孤街醉人 提交于 2020-05-14 17:44:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!