MaterialCardView:无法在xml布局中设置选中状态

时间:2019-10-31 13:07:25

标签: android materialcardview

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中设置检查状态。像这样的SMT:

android:checked_state="true"

但是我得到编译错误

2 个答案:

答案 0 :(得分:2)

对于toggle,有一种方法MaterialCardView

示例:

cardPaymentCardView.setOnClickListener {
    cardPaymentCardView.toggle()
}

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

答案 1 :(得分:1)

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

可检查卡

  

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

MaterialCardView documentation