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

瘦欲@ 提交于 2019-12-22 03:48:37

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/27474279/ripples-not-showing-with-selectableitembackground-as-foreground-on-a-cardview-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!