3

Android Studio 3.6

In xml layout I has this:

 <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" />

To turn on/off checked state I use this (in my acitivity)

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

and it's work fine. Nice.

But I need to set checked status direct in xml. Smt like this:

android:checked_state="true"

but I get compile error

Bolt UIX
  • 5,988
  • 6
  • 31
  • 58
Alexei
  • 14,350
  • 37
  • 121
  • 240
  • 1
    "Cards implement Checkable, a default way to switch to android:checked_state is not provided. Clients have to call setChecked(boolean). This shows the app:checkedIcon and changes the overlay color." from [MaterialCardView documentation](https://developer.android.com/reference/com/google/android/material/card/MaterialCardView) – NPovlsen Oct 31 '19 at 13:17

2 Answers2

3

A default way of switching to checked state is not provided, clients have to call setChecked(boolean) on the card

Checkable Cards

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 documentation

NPovlsen
  • 337
  • 1
  • 16
Zeeshan
  • 11,851
  • 21
  • 73
  • 98
2

There is a method toggle for MaterialCardView.

Example:

cardPaymentCardView.setOnClickListener {
    cardPaymentCardView.toggle()
}

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

m02ph3u5
  • 3,022
  • 7
  • 38
  • 51
Joshua
  • 61
  • 1
  • 9