从内置的Android样式中获取主题属性

时间:2014-02-22 00:21:53

标签: android android-theme android-styles

鉴于以AppTheme为主题的上下文(如下所示),是否可以通过编程方式获取颜色#ff11cc00 而无需引用R.style.MyButtonStyle,{{1} },或R.style.AppTheme

目标是获取由主题设置的按钮文本颜色,而不受特定主题或应用程序声明的资源的约束。使用android.R.style.Theme_Lightandroid.R.style.Widget_Button是可以的。

android.R.attr.textColor

2 个答案:

答案 0 :(得分:3)

尝试以下方法:

    TypedValue outValue = new TypedValue();
    Theme theme = context.getTheme();
    theme.resolveAttribute(android.R.attr.buttonStyle, outValue , true);
    int[] attributes = new int[1];
    attributes[0] = android.R.attr.textColor;
    TypedArray styledAttributes = theme.obtainStyledAttributes(outValue.resourceId, attributes);
    int color = styledAttributes.getColor(0, 0);

答案 1 :(得分:0)

我可以想到这一轮的方式,可能是其他人会更清楚:

int theme ;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD) {
  theme = android.R.style.Theme;
} else {
  theme = android.R.style.Theme_DeviceDefault;
}
ContextThemeWrapper wrapper = new ContextThemeWrapper(context, theme);
Button button = new Button(wrapper);
ColorStateList colorStateList = button.getTextColors();
colorStateList.getColorForState(button.getDrawableState(), R.color.default_color);