Search code examples
androidmaterial-designmaterial-components-androidmaterialcardview

MaterialCardView: Can't set checked state in xml layout


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


Solution

  • 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