I'm trying to change the color of a CardView depending if is selected or not
I tried this, this is my card_view_color.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true"
android:color="#ABEBC6"/> <!-- selected -->
<item android:state_selected="false"
android:color="#FFFFFF"/> <!-- not selected -->
</selector>
This is my CardView:
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
app:cardBackgroundColor="@color/card_view_color"
android:id="@+id/cardViewMetric">
</androidx.cardview.widget.CardView>
Also tried with android:state_activated, android:state_checked and is the same result, not working.
I also have a onClickListener (Kotlin):
holder.binding.root.setOnClickListener{
val GREEN_COLOR = Color.parseColor("#ABEBC6")
holder.binding.cardViewMetric.setCardBackgroundColor(GREEN_COLOR)
}
That has this current behavior.

The wanted behavior I want is only one CardView is gonna be colored, and if I select another one that one is gonna be green and the previous selection is gonna be white.
You can use the
MaterialCardViewin the Material Components Library.Then in your code:
The
MaterialCardViewextends theandroidx.cardview.widget.CardViewand support thecheckingstate.To customize the color you can use the
app:cardForegroundColorattribute:with:
or you can override the
colorPrimaryin the card:with:
By default the checked card has also a checked icon on the top right corner. You can customize it using the
app:checkedIconattribute or you can hide it usingapp:checkedIcon="@null".