8

This is my app theme:

<style name="BaseTheme" parent="Theme.AppCompat.Light">
   ...
   <item name="colorControlActivated">@color/default_orange</item>
   ...
</style>
...
<style name="Switch" parent="Material.Widget.Switch">
   <item name="colorControlActivated">@color/default_green</item>
</style>

And if I use the Switch style:

<com.rey.material.widget.Switch
     style="@style/Switch"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:checked="false"/>

The colorControlActivated used it's the one inside the BaseTheme (orange) instead of the Switch one (green).
Why is this happening? Can't I have different colorControlActivated for different Views?

Thanks.

GuilhE
  • 11,591
  • 16
  • 75
  • 116
  • 2
    Read Chris Banes's article on [Theme vs Style](https://chris.banes.me/2014/11/12/theme-vs-style/) to understand why this doesn't work and how to achieve the desired effect. – alanv May 28 '15 at 04:15
  • Good article, I've followed Chris example and replaced "style" with "android:theme" but still doesn't work :/ – GuilhE May 28 '15 at 09:36
  • Hi @GuilhE, did you ever got to solve this? I'm in the exact same place right now – Nemesis Feb 24 '16 at 10:56
  • Hi @Nemesis no, ended up using this: https://github.com/rey5137/Material/wiki/Switch – GuilhE Feb 24 '16 at 11:11
  • 1
    well, got it working, i posted an answer here in case it helps anyone :) – Nemesis Feb 24 '16 at 12:37

1 Answers1

12

The main issue is that the attribute colorControlActivated in the theme of the activity has preference to that attribute in any custom style that you define and apply to specific views.

The solution is (and this solution overrides the attribute for all elements in the same activity in the same way) to create a new theme and apply that theme to your activity in the manifest. This theme could inherit from your main theme and override only the attributes you need.

The themes:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- items-->
    <item name="colorControlActivated">@android:color/white</item>
    <!-- items-->
</style>

<style name="lightAppTheme" parent="AppTheme" >
    <item name="colorControlActivated">@color/colorPrimary</item>
</style>

The manifest:

<application
    android:name=".application.appname"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main"
        android:theme="@style/lightAppTheme"
        android:screenOrientation="portrait"></activity>
 </application>

I hope this helps anyone that comes into this since it took me some hours to get it working.

In order to make different elements in the same activity to use different colorControlActivated atributes, go to this answer.

Community
  • 1
  • 1
Nemesis
  • 1,138
  • 1
  • 14
  • 29