Domanda

Given a Context that has been themed with AppTheme (shown below), is it possible to programmatically obtain the color #ff11cc00 without referencing R.style.MyButtonStyle, R.style.AppTheme, or android.R.style.Theme_Light?

The objective is to obtain the button text color that was set by the theme without being bound to a particular theme or app-declared resource. Using android.R.style.Widget_Button and android.R.attr.textColor is okay.

<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>
È stato utile?

Soluzione

Try the following:

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

Altri suggerimenti

I can think of this round about way, may be someone else will know better:

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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top