SwitchCompat 控件颜色的修改

2,685 阅读1分钟

在开发中经常见到切换开关的 UI 需求,在 android.support.v7.widget 包下,有个开关控件叫做 SwitchCompat,但是在 xml 下并没有发现它有一个属性是用来更改颜色的。

但是在 style 中,有一个属性叫 colorControlActivated,它控制着 CheckBox、EditText、Switch、Spinner、RadioButton 等控件的默认色调,通过这个属性我们就可以修改开关的颜色了。

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="colorControlActivated">@color/Orange</item>
</style>

如果觉得点击时有个方形的背景很别扭,可以在 xml 文件中,将 SwitchCompat 的背景设置为 @null。这样就不会出现一个点击时的半透明方格了。

<android.support.v7.widget.SwitchCompat
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@null"/>