Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ripples not showing with selectableItemBackground as foreground on a CardView with a Android 5.0 device

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.

like image 735
Yunyu Lin Avatar asked Dec 14 '14 21:12

Yunyu Lin


1 Answers

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.

like image 71
Yunyu Lin Avatar answered Oct 15 '22 04:10

Yunyu Lin