如何在Android中以编程方式将色调应用于CheckBox首选项?
由于主题的原因,CheckBox首选项已经显示为灰色,但我需要通过编程将色调应用/更改为其他颜色。如何做到这一点?
发布于 2019-11-19 12:31:59
通过使用主题属性并设置colorControlNormal和colorControlActivated,可以对复选框进行着色:
styles.xml
<style name="MyCheckBox" parent="Theme.AppCompat.Light">
<item name="colorControlNormal">@color/indigo</item>
<item name="colorControlActivated">@color/pink</item>
</style>
布局xml:
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Check Box"
android:theme="@style/MyCheckBox"/>
发布于 2019-11-19 12:42:41
我推荐来自How to change checkbox checked color programmatically的@ywwynm答案
public static void setCheckBoxColor(AppCompatCheckBox checkBox, int uncheckedColor, int checkedColor) {
ColorStateList colorStateList = new ColorStateList(
new int[][] {
new int[] { -android.R.attr.state_checked }, // unchecked
new int[] { android.R.attr.state_checked } // checked
},
new int[] {
uncheckedColor,
checkedColor
}
);
checkBox.setSupportButtonTintList(colorStateList);
}
使用ColorStateList
设置setSupportButtonTintList
,然后以编程方式设置选中和取消选中状态肯定会得到您的答案
https://stackoverflow.com/questions/58934145
复制