Search code examples
androidandroid-xmlandroid-theme

Android multi color.xml selection


Suppose I have defined two themes in my App: AppTheme.Blue and AppTheme.Green, and correspondingly, I would like have set of color, thus I could apply it according two different theme.

For example, when I call ContextCompat.getColor(context, R.color.color_primary); under AppTheme.Green it will return a green color as ?attr/colorPrimary but Blue if under AppTheme.Blue, thus the the widget will always be the same color as title bar.

How can I define those two set of colors thus is system will choose it dynamically according to the current theme adopted?


Solution

  • As far as I got, you are talking about using multiple theme. Here is a scenario for your question.

    Define two themes in styles.xml

    Theme Blue:

     <style name="AppTheme.Blue" parent="Theme.AppCompat.Light.DarkActionBar">
            <item name="colorPrimary">@color/primaryColor_blue</item>
            <item name="colorPrimaryDark">@color/primaryColorDark_blue</item>
            <item name="colorAccent">@color/primaryAccent_blue</item>
            <item name="backgroundColor">@color/primaryColorDark_blue</item>
        </style>
    

    Theme Green:

    <style name="AppTheme.Green" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/primaryColor_green</item>
        <item name="colorPrimaryDark">@color/primaryColorDark_green</item>
        <item name="colorAccent">@color/primaryAccent_green</item>
        <item name="backgroundColor">@color/primaryColorDark_green</item>
    </style>
    

    Define all the colors in color.xml accordingly

    Add the following code to Get the Primary Color of the selected theme and set it to your widget.

    TypedValue typedValue = new TypedValue();
    Resources.Theme theme = this.getTheme();
    theme.resolveAttribute(android.R.attr.textColorPrimary, typedValue, true);
    TypedArray arr =
            this.obtainStyledAttributes(typedValue.data, new int[]{
                    android.R.attr.colorPrimary});
    int primaryColor = arr.getColor(0, -1);
    yourTextView.setTextColor(primaryColor);  //ex
    arr.recycle();
    

    If your selected theme is Blue then the textcolor will be blue as well. Hope this suffices.