I'm referring to the answer at https://stackoverflow.com/a/24475228/72437
The proposed answer is using drawable from Android : ?android:attr/selectableItemBackground
This is what happen when I tap on the card item. Note that, by using drawable from Android, android:state_selected="true"
(when setSelected(true)
) will not have any color change effect.
Hence, I would like to use my own defined drawable so that
- It looks nicer.
- Able to handle
android:state_selected="true"
.
Here's my code
statelist_item_background.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="@drawable/selected_background" />
<item android:state_selected="true" android:drawable="@drawable/selected_background" />
<item android:drawable="@android:color/transparent" />
</selector>
selected_background.xml
<shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffe1b3" />
<stroke
android:width="1px"
android:color="#fff76d3c" />
</shape>
card_row.xml
<!-- A CardView that contains a TextView -->
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:clickable="true"
android:foreground="@drawable/statelist_item_background"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:padding="5dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/txt_label_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
tools:text="Item Number One" />
<TextView
android:id="@+id/txt_date_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
tools:text="Item Number One" />
</LinearLayout>
</android.support.v7.widget.CardView>
When I long press on the card item and perform childView.setSelected(true);
, here's my outcome.
All my card content (TextView
s) are blocked. How can I avoid such?
Some notes regarding using android:background
Note, when you use android:background="@drawable/statelist_item_background"
with CardView
itself, nothing will happen.
However, if you use android:background="@drawable/statelist_item_background"
with CardView
's LinearLayout
, you will get the following imperfect outcome.
The highlighted color doesn't cover the entire card.
Update
Seem like this is limitation of CardView
- https://code.google.com/p/android/issues/detail?id=78198 Using "foreground" as workaround is not an option as it covers card content.