I am new to Material Card view and I want to change the card Foreground color programmatically when it is long pressed. But the parameter to the setCardForegroundColor() method requires an instance of ColorStateList to be passed and I dont know how to create ColorStateList instance for my needs.
So can anyone please tell me how to use the ColorStateList to highlight cardview when it is long pressed ?
Instead of using the ColorStateList, to change colors of my RecyclerView items when they are pressed I use a drawable
item in the background
of the list item. Here's how I implement it:
List item example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/list_item_selector"
android:padding="8dp">
<!-- Above: android:background defines the list item Touch Selector to highlight row -->
<TextView
android:id="@+id/rating_name_textview"
style="@style/EditorFieldStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="@color/colorStatListItemText"
android:textSize="18sp" />
<TextView
android:id="@+id/rating_score_textview"
style="@style/EditorFieldStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="end"
android:textColor="@color/colorStatListItemText"
android:textSize="18sp"
tools:text="100" />
</LinearLayout>
List item selector example:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Adding Touch Selectors for when items in the RecyclerView are touched -->
<!-- Three states: pressed, activated, and selected -->
<item android:drawable="@color/colorPrimaryLight" android:state_pressed="true" />
<item android:drawable="@color/colorPrimaryLight" android:state_activated="true" />
<item android:drawable="@color/colorPrimaryLight" android:state_selected="true" />
<!-- Define background color for Touch Selectors when item is not selected (light gray) -->
<item android:drawable="@color/colorBackgroundLight" />
</selector>
The list item references the list item selector and highlights the RecyclerView item appropriately, based on the colors I've defined in the color value file.