Android SwitchCompat 自定义颜色 及使用

来源:互联网 发布:软件测试工程师职责 编辑:程序博客网 时间:2024/06/06 00:00

在Android 5.0 中 Switch 更新了样式 变得 比较好用了
但是在5.0 以下的版本 还是老样子 不实用 因此 就有了 SwitchCompat 来兼容 它是v7 包中的 因此可兼容到 2.1

使用时 写一下布局即可。。

<android.support.v7.widget.SwitchCompat        android:id="@+id/switch1"        android:layout_width="wrap_content"        android:layout_height="wrap_content" /> 

这个switch 默认是 粉红色的 有的时候我们需要设置成和我们的主题颜色一致 就需要更改 switch的颜色
一种方式是 设置 thumb(拇指按钮) 和 track(轨迹) 颜色

switch1 = (SwitchCompat) view.findViewById(R.id.switch1);        switch1.setTrackResource();        switch1.setThumbResource();

如果有适合的图片 可以这样设置 但是通常这样设置是比较麻烦的 需要合适的图片
因此就有了下面的简便的方法 :

在style 中设置

  <!-- Active thumb color & Active track color(30% transparency) switch 打开时的拇指按钮的颜色 轨迹颜色默认为30%这个颜色 -->              <item name="colorControlActivated">@color/theme_color_green</item>            <!-- Inactive thumb color switch关闭时的拇指按钮的颜色 -->            <item name="colorSwitchThumbNormal">@color/colorAccent</item>            <!-- Inactive track color(30% transparency) switch关闭时的轨迹的颜色  30%这个颜色 -->            <item name="android:colorForeground">@color/colorPrimaryDark</item>

这样就完成了

1 3
原创粉丝点击