使用Android 5.0设备在CardView上将selectableItemBackground显示为前景的涟漪

yun*_*nyu 10 android android-cardview rippledrawable android-5.0-lollipop

我在Nexus 5上运行它.这是我的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);
Run Code Online (Sandbox Code Playgroud)

这是我如何获得selectedItemDrawable:

        int[] attrs = new int[] { R.attr.selectableItemBackground };
        TypedArray ta = getActivity().obtainStyledAttributes(attrs);
        selectedItemDrawable = ta.getDrawable(0);
        ta.recycle();
Run Code Online (Sandbox Code Playgroud)

当我点击卡片时,不会出现与selectedItemDrawable一起出现的波纹(它看起来与没有前景设置完全相同).我正在运行5.0,所以这看起来很奇怪,因为appcompat文档只说它不适用于pre-Lollipop设备.有人知道为什么会这样吗?最低API级别为16,目标为21.

yun*_*nyu 9

事实证明,我正在与多个卡片视图共享我的Drawable实例.通过使用getSelectedItemDrawable方法返回一个新实例解决了这个问题:

    public Drawable getSelectedItemDrawable() {
        int[] attrs = new int[]{R.attr.selectableItemBackground};
        TypedArray ta = getActivity().obtainStyledAttributes(attrs);
        Drawable selectedItemDrawable = ta.getDrawable(0);
        ta.recycle();
        return selectedItemDrawable;
    }
Run Code Online (Sandbox Code Playgroud)

然后以编程方式将其设置为前景:

        cardView.setForeground(getSelectedItemDrawable());
        cardView.setClickable(true);
Run Code Online (Sandbox Code Playgroud)

现在我得到5.0的涟漪效果.