CardView background color states not being respected
Though this is not ideal, since the edges are not rounded, you can add touch feedback to a CardView
like this :
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="4dp"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground">
//Nested View ...
</android.support.v7.widget.CardView>
Adding the android:foreground
and android:clickable
attributes to the CardView
.
Also this has a negative side effect in that the android:clickable
attribute overrides any clickListener, and therefore those clickListeners don't get triggered.
Update
I have some examples of CardView implementations
Loop (https://github.com/lawloretienne/Loop) - https://github.com/lawloretienne/Loop/blob/master/app/src/main/res/layout/category_card.xml
QuickReturn (https://github.com/lawloretienne/QuickReturn) - https://github.com/lawloretienne/QuickReturn/blob/master/sample/src/main/res/layout/activity_quick_return.xml
Update 2
After more research I have come up with a good solution for CardViews on all API versions including pre-Lollipop.
https://medium.com/@etiennelawlor/layout-tips-for-pre-and-post-lollipop-bcb2e4cdd6b2#.9h0v1gmaw
Here's my way to solve your problem.
First, create a custom class named CustomCardView
extends CardView
Then override the drawableStateChanged()
method, change the card background color by call setCardBackgroundColor()
method when card's press status changed.
Last, replace the CardView with this CustomCardView in you layout file.
the only one disadvantage of this solution is cardview can't display ripple press effect on Android 5.0 and above.
here's my code:
public class CustomCardView extends CardView {
public CustomCardView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public CustomCardView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public CustomCardView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
if (isPressed()) {
this.setCardBackgroundColor(getContext().getResources().getColor(R.color.card_view_pressed));
} else {
this.setCardBackgroundColor(getContext().getResources().getColor(R.color.card_view_normal));
}
}
}
Sometimes, you may want the CardView
to have visual touch feedback. The android:foreground="?android:attr/selectableItemBackground"
solution is perfect for this.
However, you may consider using drawSelectorOnTop(true)
with your ListView. This will require no change on your CardView
at all.
Let me know if further clarification is needed.