从主题获取EditText的“默认”颜色值

时间:2011-12-22 01:22:27

标签: android android-layout android-theme

我的Activity在3.1上包含EditText。根据用户输入,我更改EditText中的文本颜色(红色表示错误),然后在文本正常时将其重置为黑色。

一个问题涉及更改活动的整体主题。例如,将它从灯光主题更改为常规黑暗主题会导致黑色文本显示在黑色背景下 - 所以我需要进入并更改代码,而不是在数据正常时将文本重置为白色。 / p>

如果我对Activity进行主题更改,而不是必须更改此代码,我想知道是否有办法以编程方式为给定主题提取默认的EditText文本颜色,然后我可以将文本切换回默认颜色,而不是白色,黑色等硬编码

3 个答案:

答案 0 :(得分:11)

根据Theme's docs直接使用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();
}

答案 1 :(得分:8)

使用R.attr

setTextColor(android.R.attr.editTextColor)

答案 2 :(得分:4)

如果在更改颜色之前检索它们,

EditText.getCurrentTextColor()EditText.getTextColors()也会提供默认颜色。此外,这种方法可以在3.0之前使用,这在使用android.R.attr.editTextColor时是不可能的。