鉴于以AppTheme
为主题的上下文(如下所示),是否可以通过编程方式获取颜色#ff11cc00 而无需引用R.style.MyButtonStyle
,{{1} },或R.style.AppTheme
?
目标是获取由主题设置的按钮文本颜色,而不受特定主题或应用程序声明的资源的约束。使用android.R.style.Theme_Light
和android.R.style.Widget_Button
是可以的。
android.R.attr.textColor
答案 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);