我如何改变默认的复选框的颜色在Android? 默认情况下,复选框的颜色是绿色,我想改变这个颜色。 如果不可能,请告诉我如何做一个自定义复选框?


当前回答

你可以创建自己的XML在drawable和使用这作为android:background="@drawable/your_xml"

这样你就可以给边角任何东西

<item>
    <shape>
        <gradient

            android:endColor="#fff"
            android:startColor="#fff"/>
        <corners
            android:radius="2dp"/>
        <stroke
            android:width="15dp"
            android:color="#0013669e"/>

    </shape>
</item>

其他回答

你可以创建自己的XML在drawable和使用这作为android:background="@drawable/your_xml"

这样你就可以给边角任何东西

<item>
    <shape>
        <gradient

            android:endColor="#fff"
            android:startColor="#fff"/>
        <corners
            android:radius="2dp"/>
        <stroke
            android:width="15dp"
            android:color="#0013669e"/>

    </shape>
</item>

您可以使用下面的代码行在java代码中动态更改复选框的背景。

//Setting up background color on checkbox.
 checkbox.setBackgroundColor(Color.parseColor("#00e2a5"));

这个答案来自这个网站。你也可以使用这个网站将你的RGB颜色转换为十六进制值,你需要提供parseColor

如果你打算使用android图标,如上所述..

android:button="@android:drawable/..."

. .这是一个不错的选择,但为了让它工作-我发现你需要添加切换逻辑来显示/隐藏复选标记,就像这样:

    checkBoxShowPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        // checkbox status is changed from uncheck to checked.
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            int btnDrawable = android.R.drawable.checkbox_off_background;

            if (isChecked)
            {
                btnDrawable = android.R.drawable.checkbox_on_background;
            }

            checkBoxShowPwd.setButtonDrawable(btnDrawable);

        }
    });

如果你的minSdkVersion是21+使用android:buttonTint属性来更新复选框的颜色:

<CheckBox
  ...
  android:buttonTint="@color/tint_color" />

在使用AppCompat库和支持低于21的Android版本的项目中,你可以使用buttonTint属性的compat版本:

<CheckBox
  ...
  app:buttonTint="@color/tint_color" />

在这种情况下,如果你想子类化一个CheckBox,不要忘记使用AppCompatCheckBox代替。

之前的回答:

你可以使用android:button="@drawable/your_check_drawable"属性来改变checkboxes的可绘制性。

100%鲁棒方法。

在我的情况下,我没有访问XML布局源文件,因为我从第三方MaterialDialog库获得复选框。 所以我必须通过编程来解决这个问题。

在xml中创建ColorStateList:

res /颜色/ checkbox_tinit_dark_theme.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/white"
        android:state_checked="false"/>
    <item android:color="@color/positiveButtonBg"
        android:state_checked="true"/>
</selector>

然后应用到复选框: ColorStateList darkStateList = ContextCompat.getColorStateList(getContext(), R.color.checkbox_tint_dark_theme); CompoundButtonCompat。darkStateList setButtonTintList(复选框);

另外,如果有人感兴趣,下面是如何从MaterialDialog对话框中获得复选框(如果你设置了.checkBoxPromptRes(…)):

CheckBox checkbox = (CheckBox) dialog.getView().findViewById(R.id.md_promptCheckbox);

希望这能有所帮助。