一:使用主题色
1.给View设置主题
<style name="MyCheckBoxTheme" parent="Base.Widget.AppCompat.CompoundButton.CheckBox">
<item name="colorControlActivated">#0FF</item>
<item name="colorControlNormal">#FFF</item>
</style>
<android.support.v7.widget.AppCompatCheckBox
android:theme="@style/MyCheckBoxTheme"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
2.给Activity设置主题
<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">#0FF</item>
<item name="colorControlNormal">#FFF</item>
</style>
然后将AppTheme设置给对应的Activity
其实主要是colorControlActivated和colorControlNormal在控制它的颜色,colorControlNormal是指正常情况下的颜色,也就是checked等于false的时候的颜色;colorControlActivated是指选中时的颜色,也就是checked等于true的时候的颜色。
当没有给定colorControlActivated对应的颜色时那么colorAccent对应的颜色就决定了它选中的颜色。
弊端:只能在加载布局的时候应用主题颜色,不能通过代码动态改变颜色。
二:buttonTint着色
<android.support.v7.widget.AppCompatCheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:buttonTint="@color/colorPrimary"/>
如果传入的是一个颜色值那就是给整个勾选框染上指定的颜色,在这里也可以写一个颜色选择器,通过状态给勾选框着色。
弊端:有API版本限制,最低可用于android5.0,低于android5.0的设备是无法修改颜色的,同样只能在加载布局的时候应用颜色。
三:setButtonTintList和setSupportButtonTintList
- checkbox.setButtonTintList可以动态修改颜色,但是有API版本限制,最低可用于android5.0的设备。
AppCompatCheckBox checkbox = findViewById(R.id.checkbox);
checkbox.setButtonTintList(ColorStateList.valueOf(Color.CYAN));
2.checkbox.setSupportButtonTintList这个方法并没有暴露出来给开发者使用,仅仅用于support v4包里面。
/**
* This should be accessed from {@link android.support.v4.widget.CompoundButtonCompat}
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
@Override
public void setSupportButtonTintList(@Nullable ColorStateList tint) {
if (mCompoundButtonHelper != null) {
mCompoundButtonHelper.setSupportButtonTintList(tint);
}
}
四:使用CompoundButtonCompat类
这个类一看就知道是兼容用的,用法其实很简单:
AppCompatCheckBox checkbox = findViewById(R.id.checkbox);
CompoundButtonCompat.setButtonTintList(checkbox,ColorStateList.valueOf(Color.CYAN));
其实不能使用的setSupportButtonTintList这个方法里面也是调用CompoundButtonCompat.setButtonTintList实现着色的。
五:总结
动态修改AppCompatCheckBox和AppCompatRadioButton的颜色就使用CompoundButtonCompat.setButtonTintList;布局里面应用颜色就使用主题去修改。