【发布时间】:2021-11-27 12:18:49
【问题描述】:
我有一个 Checkbox,在 selector 中包含自定义图像...
我试图在点击checkbox时达到以下效果:
Gif 供参考:
当按下 checkbox 时背景必须改变,然后在释放时恢复正常。
前两个按钮是ImageButtons,效果很容易实现,但是Checkbox我很挣扎。
我想它必须与selector 本身有关,但我不太确定如何实现它。我尝试在item 和solid 颜色中添加shape,但我无法使其工作。请指出正确的方向。
下面是我的复选框代码(它使用双向数据绑定):
<CheckBox
android:id="@+id/btn_addtofavs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/inflated_selector_is_checked"
android:button="@null"
android:checked="@={inflatedItemViewModel.item.checked}"
android:onClick="@{() -> inflatedItemViewModel.updateChecked(inflatedItemViewModel.item.id, inflatedItemViewModel.item.checked)}"
tools:ignore="ContentDescription" />
我的Checkbox 选择器:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@drawable/ic_inflated_star_outline"
android:state_checked="false"/>
<item
android:drawable="@drawable/ic_inflated_star_full"
android:state_checked="true"/>
<item
android:drawable="@drawable/ic_inflated_star_outline"/>
</selector>
其他 2 个按钮选择器:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape>
<solid android:color="@color/blue_200"/>
<corners android:radius="@dimen/_8sdp"/>
</shape>
</item>
<item android:state_pressed="false">
<shape>
<solid android:color="@color/blue_500"/>
<corners android:radius="@dimen/_8sdp"/>
</shape>
</item>
</selector>
更新 1:Tenfour04 建议
<com.google.android.material.button.MaterialButton
android:id="@+id/btn_addtofavs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="@drawable/bg_button"
android:checkable="true"
android:checked="@={inflatedItemViewModel.item.checked}"
android:onClick="@{() -> inflatedItemViewModel.updateChecked(inflatedItemViewModel.item.id, inflatedItemViewModel.item.checked)}"
app:icon="@drawable/inflated_selector_is_checked"
app:iconGravity="textStart"
app:iconPadding="0dp"
tools:ignore="ContentDescription" />
出现错误:
Cannot find a getter for <com.google.android.material.button.MaterialButton android:checked> that accepts parameter type 'boolean'
即编译器无法将其识别为两阶段按钮。我错过了什么吗?
【问题讨论】:
-
为什么不使用普通的 imageview 而不是 checkbox 。维护一个标志并点击切换标志和带有选中图像的图像。
-
我猜是因为双向数据绑定
-
@pepper90,您是否尝试使用
android:state_pressed="true"向您的inflated_selector_is_checked添加状态? -
@Demigod 请给我看我案例中的代码。
标签: android xml kotlin checkbox android-checkbox