1

I am trying to change color of my card view when someone click on it. So far I have tried using this code below:

 //drawable/selector.xml
<?xml version="1.0" encoding="utf-8"?>
   <selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_pressed="true"android:drawable="@color/button_pressed"/> <!-- pressed -->
   <item android:state_focused="true" android:drawable="@color/button_focused"/> <!-- focused --> 
  <item android:drawable="@color/button_default"/> <!-- default -->
</selector>

This is my selector code this works perfect when I use this in button code is below:

<Button
  android:id="@+id/button1"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:background="@drawable/selector"
  android:text="Click Me"
 />

I am trying to do this inside card view I can't see anything inside my card view I am using selector like this:

  <android.support.v7.widget.CardView
    android:foreground="?android:attr/selectableItemBackground"
    android:clickable="true"
    android:layout_width="170dp"
    android:layout_height="150dp"
    android:layout_margin="4dp"
    android:onClick="economy"
    android:background="@drawable/selector"
    >
   </android.support.v7.widget.CardView>

My card is clickable my question is can I do this inside card view

Nilay Singh
  • 2,201
  • 6
  • 31
  • 61
  • there is a limitation with Cardview on changing the background using selector. refer [https://stackoverflow.com/questions/33763403/cardviews-background-which-will-respond-to-androidstate-selected-and-androids](https://stackoverflow.com/questions/33763403/cardviews-background-which-will-respond-to-androidstate-selected-and-androids). – rafa May 21 '18 at 06:49

1 Answers1

1

There is a limitation with Cardview on changing the background using selector.If You still want to go ahead with that. You can apply selector on foreground.

<android.support.v7.widget.CardView
   android:foreground="@drawable/selector"  // change
    android:clickable="true"
    android:layout_width="170dp"
    android:layout_height="150dp"
    android:layout_margin="4dp"
    android:onClick="economy"
    >
   </android.support.v7.widget.CardView>

And add alpha to the color(like : #55FFFFFF) which you are applying on the selector so that the content of the card will be visible. This is not ideal but depends on your output expectation.

rafa
  • 1,319
  • 8
  • 20