Android: Change the color of RadioButtons and checkboxes programmatically

前端 未结 6 1207
轮回少年
轮回少年 2020-12-15 08:11

I created RadioButton and CheckBox in LinearLayout programatically. But, now I want to change radio button\'s color and check boxes\'s

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-15 08:40

    I am continuing the answer of ywwynm.

    Google made the setSupportButtonTintList restricted so it is not possible to use it.

    The workaround is to use the button as a TintableCompoundButton interface, in which the method is not restricted.

    Works in API 19+ for AppCompatRadioButton. AppCompatCheckbox implements the same interface so it should work as well in theory but I haven't tested it.

    Have fun :)

    public static void setAppCompatRadioButtonColor(AppCompatRadioButton radioButton, 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
                }
        );
        ((TintableCompoundButton) radioButton).setSupportButtonTintList(colorStateList);
    }
    

提交回复
热议问题