矩形形状的可绘制对象无法显示为复选框选择器项

8

我已经定义了一个矩形的drawable,如下所示:

<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">

    <corners android:radius="4dip"/>
    <solid android:color="#FF000000" />
    <stroke android:width="1dip" android:color="@color/service_checkbox_disabled_unchecked_stroke" />

</shape>

我可以将Drawable显示为ImageView,没有问题。然而,它应该是一个复选框的一种状态的Drawable。我的复选框按钮选择器定义如下:

<selector xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:state_checked="true" android:drawable="@drawable/bg_services_tick_unchecked_disabled" />
    <item android:state_checked="false" android:drawable="@drawable/bg_services_tick_unchecked_disabled" />

</selector>

最后是我的复选框:

<CheckBox
    android:id="@+id/cb_tariff_3_next_month_checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:button="@drawable/checkbox_services"
    android:layout_centerHorizontal="true"/>

有人能告诉我,为什么这行代码不起作用吗?非常感谢。

1
请接受下面的答案。这是非常晦涩的知识,值得认可。(我不是发帖人)。 - Stephen Hosking
1个回答

18

你必须向形状添加一个 size 节点:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    >
    <size android:width="30dp" android:height="30dp" />
    <solid android:color="@color/blueBase"/>
    <stroke
        android:width="1dp"
        android:color="@color/blueDark" />
</shape>

2
你解救了我的一天。 - Mihir Trivedi
今天一天内已经有两个了!我疯了,试图弄清楚为什么它可以使用文件 drawable,但不能使用 XML 文件。 - PM4
这种行为对我来说似乎非常不一致。我通过将透明颜色作为按钮并将选择器作为背景来使其工作。但我的解决方法并没有让我满意,你是如何想到这个方法的?你查看了哪个文件?你怎么知道这在文档中有提到? - cutiko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接