You can customize android switch track by defining a drawable xml resource as shown below. You need to save it in res/drawable folder, our example file name switch_track_custom. xml, and apply it to switch by using track attribute.
The Switch Anatomy
To have a SwitchCompat, just add the code below in the layout
In my case, I would like the track to be pure_red as well when checked, and grey when it is not checked. Hence I set a track color selector file name as switch_color.xml in the res/color folder.
The Switch Anatomy
To have a SwitchCompat, just add the code below in the layout
<android.support.v7.widget.SwitchCompatAs for the customized, it is just adding the Style as below
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<android.support.v7.widget.SwitchCompatMost reference would guide us to change the colorControlActivated. One define the theme as below
style="@style/SwitchCompatStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<style name="SwitchCompatTheme" >Then have your SwitchCompat have the theme as below.
<item name="colorControlActivated">@color/pure_red</item>
</style>
<android.support.v7.widget.SwitchCompatChanging the color specifically
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:theme="@style/SwitchCompatTheme" />
In my case, I would like the track to be pure_red as well when checked, and grey when it is not checked. Hence I set a track color selector file name as switch_color.xml in the res/color folder.
<?xml version="1.0" encoding="utf-8"?>And set the color for the SwitchCompat’s thumb and track through the Style in style.xml
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/pure_red"
android:state_checked="true" />
<item android:color="@color/grey"/>
</selector>
<style name="SwitchCompatStyle" >Then define your SwitchCompat view by setting the appropraite Style
<item name="thumbTint">@color/switch_color</item>
<item name="trackTint">@color/switch_color</item>
</style>
<android.support.v7.widget.SwitchCompatWith this, you’ll get the track color as intended (ok, ok,I know having the same color for thumb and track looks ugly… it is fixed in the next section)
style="@style/SwitchCompatStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
No comments:
Post a Comment