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

时间:2014-12-14 21:23:26

标签: android android-5.0-lollipop android-cardview rippledrawable

我在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);

以下是我如何获得selectedItemDrawable:

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

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

1 个答案:

答案 0 :(得分: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;
    }

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

        cardView.setForeground(getSelectedItemDrawable());
        cardView.setClickable(true);

现在我在5.0上获得了涟漪效应。