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

5
给定一个使用了AppTheme主题的上下文(如下所示),是否有可能在不引用R.style.MyButtonStyleR.style.AppThemeandroid.R.style.Theme_Light的情况下以编程方式获得颜色#ff11cc00
目标是获取由主题设置的按钮文本颜色,而不受特定主题或应用程序声明资源的限制。可以使用android.R.style.Widget_Buttonandroid.R.attr.textColor
<style name="AppTheme" parent="Theme.Light">
    <item name="android:buttonStyle">@style/MyButtonStyle</item>
</style>

<style name="MyButtonStyle" parent="android:style/Widget.Button">
    <item name="android:textColor">#ff11cc00</item>
</style>

当你说不引用MyButtonStyleAppTheme时,你的意思是什么? - Manveer Chawla
我会更新问题以澄清。 - James Wald
我在问题中添加了更多细节,并提到的想法是避免被绑定到任何应用程序声明的资源,包括<color>或<style>。仅使用内置的Android样式和属性。 - James Wald
颜色和样式都取决于主题。因此,当您说要获取按钮使用的文本颜色时,它必须依赖于主题。 - Manveer Chawla
1
我已经发布了我所能想到的答案。 - Manveer Chawla
显示剩余2条评论
2个回答

5
尝试以下方法:
    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);

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);

我可以确认这种方法是可行的,但如果您已经有一个Context,那么您只需要最后三行。将主题应用到按钮是目前我唯一能够实现这个效果的方法。我相信按钮可以访问android.internal.R.styles,而这可能无法从应用程序中访问。然而,在接受此答案之前,我希望知道是否有更干净的方法来完成这项工作。 - James Wald
如果您未将默认主题应用于按钮,并且在样式中某处覆盖了按钮主题,则不会获取按钮使用的默认颜色。因此,您需要默认主题和ContextThemeWrapper。 - Manveer Chawla
没错,这个答案会从默认主题中获取颜色。在我的问题中,我试图提到我的上下文已经使用AppTheme进行了主题设置,并且我想获取已设置为android.R.style.buttonStyle的android:textColor属性的结果颜色。在两种情况下都可以使用真实的按钮。我只是希望有一种方法可以在不分配丢弃视图的情况下完成此操作。 - James Wald
然而,如果您使用ApplicationContext来创建Button,那也应该可以工作。然后您就不必去创建ContextThemeWrapper了。因为主题不会应用于ApplicationContext - Manveer Chawla
刚刚看到了你之前的评论,明白你的意思。希望有更好的方法来解决这个问题。 - Manveer Chawla

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接