MaterialCardView:无法在 xml 布局中设置选中状态
MaterialCardView: Can't set checked state in xml layout
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" />
要打开 on/off 选中状态,我使用这个(在我的活动中)
dataBinding.cardPaymentCardView.isChecked = !dataBinding.cardPaymentCardView.isChecked
它工作正常。不错
但是我需要直接在xml中设置检查状态。像这样:
android:checked_state="true"
但是我得到编译错误
没有提供切换到checked状态的默认方式,客户端必须在card上调用setChecked(boolean)
可检查卡片
Cards implement Checkable interface. In the default style, @style/Widget.MaterialComponents.CardView, the checked state shows a checked icon and changes the overlay color. A default way of switching to checked state is not provided, clients have to call setChecked(boolean) on the card. Setter for an OnCheckedChangeListener is also provided.
MaterialCardView
有一个方法 toggle
。
示例:
cardPaymentCardView.setOnClickListener {
cardPaymentCardView.toggle()
}
参考:https://developer.android.com/reference/com/google/android/material/card/MaterialCardView#toggle
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" />
要打开 on/off 选中状态,我使用这个(在我的活动中)
dataBinding.cardPaymentCardView.isChecked = !dataBinding.cardPaymentCardView.isChecked
它工作正常。不错
但是我需要直接在xml中设置检查状态。像这样:
android:checked_state="true"
但是我得到编译错误
没有提供切换到checked状态的默认方式,客户端必须在card上调用setChecked(boolean)
可检查卡片
Cards implement Checkable interface. In the default style, @style/Widget.MaterialComponents.CardView, the checked state shows a checked icon and changes the overlay color. A default way of switching to checked state is not provided, clients have to call setChecked(boolean) on the card. Setter for an OnCheckedChangeListener is also provided.
MaterialCardView
有一个方法 toggle
。
示例:
cardPaymentCardView.setOnClickListener {
cardPaymentCardView.toggle()
}
参考:https://developer.android.com/reference/com/google/android/material/card/MaterialCardView#toggle