Home » Android » Different colorControlActivated styles in Android

Different colorControlActivated styles in Android

Posted by: admin June 15, 2020 Leave a comment

Questions:

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.

How to&Answers:

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.