Nilay Singh
Nilay Singh

Reputation: 2341

Android change hover color of card view which is clickable

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

Upvotes: 1

Views: 3562

Answers (1)

rafa
rafa

Reputation: 1369

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.

Upvotes: 1

Related Questions