1、直接使用的效果
<android.support.v7.widget.SwitchCompat android:id="@+id/switch_tog" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="false" />效果: 2、各种属性 xmlns:app=”http://schemas.android.com/apk/res-auto” 代码
<android.support.v7.widget.SwitchCompat android:id="@+id/switch_tog" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="false" android:text="我是SwitchCompat" android:textOff="关" android:textOn="开" app:showText="true" />效果
3、开关的字体大小颜色,代码
app:switchTextAppearance="@style/ontextoff"在styles.xml中
<style name="ontextoff" parent="Theme.AppCompat.Light"> <item name="android:textColor">#0d09f1</item> <item name="android:textSize">8sp</item> </style>效果 4、开关轨迹样式颜色 代码
app:theme="@style/scstyle"在styles.xml中
<style name="scstyle" parent="Theme.AppCompat.Light"> <!--开启时的颜色--> <item name="colorControlActivated">#00e6db</item> <!--关闭时的颜色--> <item name="colorSwitchThumbNormal">#383434</item> <!--关闭时的轨迹颜色--> <item name="android:colorForeground">#ecd502</item> </style>效果 5、宽度设置和距离文字设置
app:switchMinWidth="60dp" app:switchPadding="50dp"效果
6、轨道颜色和按钮颜色
app:trackTint="#cc1023" app:thumbTint="#10cc16"效果
7、开关监听
switchTog.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { } });8、代码设置轨道和按钮
switchTog.setTrackResource(R.mipmap.ic_launcher); switchTog.setThumbResource(R.mipmap.ic_launcher);setThumbResource还可以用selector,如
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="true" android:drawable="@drawable/ic_c"/> <item android:state_checked="false" android:drawable="@drawable/ic_v"/> <item android:drawable="@drawable/ic_s"/> </selector>