【问题标题】:MaterialCardView: Can't set checked state in xml layoutMaterialCardView:无法在 xml 布局中设置选中状态
【发布时间】:2020-02-26 20:31:33
【问题描述】:

Android Studio 3.6

在 xml 布局中我有这个:

 <com.google.android.material.card.MaterialCardView
                android:id="@+id/cardPaymentCardView"
                style="@style/cardViewStyle"
                android:layout_width="0dp"
                android:layout_height="0dp"
                app:checkedIcon="@drawable/ic_credit_card_outline_select"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

要打开/关闭检查状态,我使用它(在我的活动中)

dataBinding.cardPaymentCardView.isChecked = !dataBinding.cardPaymentCardView.isChecked

它工作正常。不错。

但我需要直接在 xml 中设置检查状态。像这样:

android:checked_state="true"

但我得到编译错误

【问题讨论】:

  • "卡片实现了 Checkable,没有提供切换到 android:checked_state 的默认方式。客户端必须调用 setChecked(boolean)。这会显示 app:checkedIcon 并更改覆盖颜色。"来自MaterialCardView documentation

标签: android material-design material-components-android materialcardview


【解决方案1】:

没有提供切换到检查状态的默认方式,客户端必须在卡上调用 setChecked(boolean)

可检查卡片

卡片实现了 Checkable 接口。在默认样式@style/Widget.MaterialComponents.CardView 中,选中状态显示选中图标并更改覆盖颜色。没有提供切换到检查状态的默认方法,客户端必须在卡上调用 setChecked(boolean)。还提供了 OnCheckedChangeListener 的 Setter。

MaterialCardView documentation

【讨论】:

    【解决方案2】:

    MaterialCardView 有一个方法 toggle

    例子:

    cardPaymentCardView.setOnClickListener {
        cardPaymentCardView.toggle()
    }
    

    参考:https://developer.android.com/reference/com/google/android/material/card/MaterialCardView#toggle

    【讨论】:

    • 它可以工作,但我在 onLongClick 侦听器中尝试了相同的代码不工作
    猜你喜欢
    • 2019-07-19
    • 2014-12-11
    • 1970-01-01
    • 2011-10-25
    • 2020-08-26
    • 2017-03-05
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多