I'm running this on a Nexus 5. Here's part of the code for my CardView:
        CardView cardView = new CardView(getActivity());
        cardView.setRadius(4);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 400);
        lp.setMargins(32, 16, 32, 16);
        cardView.setLayoutParams(lp);
        cardView.setContentPadding(50, 50, 50, 50);
        ...
        cardView.setForeground(selectedItemDrawable);
And here's how I get the selectedItemDrawable:
        int[] attrs = new int[] { R.attr.selectableItemBackground };
        TypedArray ta = getActivity().obtainStyledAttributes(attrs);
        selectedItemDrawable = ta.getDrawable(0);
        ta.recycle();
When I tap the card, the ripple that's supposed to come with the selectedItemDrawable does not appear (it looks exactly the same as without the foreground set). I am running 5.0, so this seems strange, as the appcompat docs only say that it doesn't work with pre-Lollipop devices. Does anybody know why this is the case? Minimum API level is 16, targetting 21.
It turned out that I was sharing my instance of the Drawable with multiple cardviews. This was resolved by returning a new instance using a getSelectedItemDrawable method:
    public Drawable getSelectedItemDrawable() {
        int[] attrs = new int[]{R.attr.selectableItemBackground};
        TypedArray ta = getActivity().obtainStyledAttributes(attrs);
        Drawable selectedItemDrawable = ta.getDrawable(0);
        ta.recycle();
        return selectedItemDrawable;
    }
Then setting it as the foreground programatically:
        cardView.setForeground(getSelectedItemDrawable());
        cardView.setClickable(true);
Now I get the ripple effect on 5.0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With