首页 > 解决方案 > 设置按钮属性时,Android CheckBox 用纯色填充

问题描述

比较简单的情况。我有一个复选框,我将按钮属性设置为我的选择器,其中有两个可绘制对象用于选中和未选中。它在编辑器中看起来很合适,但是当我实际启动应用程序时,它会被纯色填充。

在编辑器中

在此处输入图像描述

在实际应用中

在此处输入图像描述

这是 XML

     <CheckBox
            android:id="@+id/selected_checkBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:button="@drawable/checkbox_states"
            android:clickable="false"
            android:checked="false"
            android:visibility="invisible" />

这是 checkbox_states 可绘制的

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

检查的

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="48dp"
    android:height="48dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    >
  <path
      android:pathData="M2,1L22,1A1,1 0,0 1,23 2L23,22A1,1 0,0 1,22 23L2,23A1,1 0,0 1,1 22L1,2A1,1 0,0 1,2 1z"
      android:strokeWidth="2"
      android:fillColor="#EAC752"
      android:strokeColor="#EAC752"/>
  <path
      android:pathData="M6,13L10,17L20,7"
      android:strokeLineJoin="round"
      android:strokeWidth="2"
      android:fillColor="#00000000"
      android:strokeColor="#0E4DA4"
      android:strokeLineCap="round"/>
</vector>

而未选中的只是一个正方形。我没有可能导致此问题的样式或任何类型的东西。但似乎这是颜色次要的。所以 AppTheme 的某些东西可能会导致这种情况。我只是不确定是什么

标签: androidandroid-layoutandroid-drawableandroid-stylesandroid-checkbox

解决方案


CheckBox 组件继承自 Button View,因此您可以使用android:background属性通过可绘制状态选择器而不是android:button来更改复选框状态。示例如下:

 <CheckBox
   android:id="@+id/selected_checkBox"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:background="@drawable/checkbox_states"
   android:button="@null"
   app:buttonCompat="@null"
   android:checked="true" />

推荐阅读