给 SwitchCompat 设置颜色的方法

来源:互联网 发布:北大青鸟java培训费用 编辑:程序博客网 时间:2024/06/07 09:52

本文介绍 SwitchCompat 控件设置颜色的方法。

安卓常见的开关控件及其样式如下图:

SwitchCompat 控件有 thumb(圆) 和 track(横条)两部分组成:

设置 thumb 和 track 的颜色的方式有两种,分别是通过 xml 和 Java 代码。

xml 方式

style.xml

 <style name="MySwitchTheme">        <item name="colorControlActivated">#FFFF6633</item>        <item name="colorSwitchThumbNormal">#FFF1F1F1</item>        <item name="android:colorForeground">#FF2F2F2F</item>    </style>

布局文件:

 <android.support.v7.widget.SwitchCompat            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_centerVertical="true"            android:layout_marginRight="5dp"            android:theme="@style/MySwitchTheme" />

java 代码方式:

  public static void setSwitchColor(SwitchCompat v) {        // thumb color        int thumbColor = 0xffFF6633;        // trackColor        int trackColor = 0xfff1f1f1;        // set the thumb color        DrawableCompat.setTintList(v.getThumbDrawable(), new ColorStateList(                new int[][]{                        new int[]{android.R.attr.state_checked},                        new int[]{}                },                new int[]{                        thumbColor,                        trackColor                }));        // set the track color        DrawableCompat.setTintList(v.getTrackDrawable(), new ColorStateList(                new int[][]{                        new int[]{android.R.attr.state_checked},                        new int[]{}                },                new int[]{                        0x4DFF6633,                        0x4d2f2f2f                }));    }

其中 xml 方式比较方便,缺点是在开和关状态下,track 会自动把 colorControlActivated 和 android:colorForeground 的颜色值加上 30%(0.3 * ff = 4D)透明度作为自己的颜色值。这一点开发者不可控。

而 Java 代码方式则可以规避这一默认规则,使得开和关状态下 track 和 thumb 的颜色完全由开发者指定。

原创粉丝点击