Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining themed attributes from built in Android styles

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>
like image 376
James Wald Avatar asked Oct 02 '22 12:10

James Wald


People also ask

Where do I get Android themes?

If you want to change up the way your Android device looks, you can easily get free Android themes from the Google Play Store.

Where are style values stored Android studio?

A style is defined in an XML resource that is separate from the XML that specifies the layout. This XML file resides under res/values/ directory of your project and will have <resources> as the root node which is mandatory for the style file. The name of the XML file is arbitrary, but it must use the . xml extension.

Which XML is used to define custom themes and looks for the UI of application?

Styles and themes are declared in a style resource file in res/values/ , usually named styles.xml .

What is the use of styles and themes in Android explain it?

Styles and Themes in Android Styles are several parameters: font, color, background, margin, text size, text style, etc. Using a combination of these properties, you can create your style and apply that style to a UI component or the whole layout.


1 Answers

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);
like image 153
Tas Morf Avatar answered Oct 05 '22 10:10

Tas Morf