在Android 5.0设备上,使用selectableItemBackground作为CardView的前景时,涟漪效果无法显示。

11

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

以下是我获取选定项Drawable的方式:

        int[] attrs = new int[] { R.attr.selectableItemBackground };
        TypedArray ta = getActivity().obtainStyledAttributes(attrs);
        selectedItemDrawable = ta.getDrawable(0);
        ta.recycle();
当我点击卡片时,应该会出现与selectedItemDrawable一起出现的涟漪效果,但是并没有出现(它看起来与没有设置前景一样)。我正在运行5.0版本,所以这似乎很奇怪,因为appcompat文档只说它不适用于Lollipop之前的设备。有人知道为什么吗?最低API级别为16,目标为21。

你确定在CardView中没有设置宽度为match_parent并且有自己的背景的视图吗? - Hellboy
我已经注释掉了任何添加视图到CardView的代码,因此布局中只有CardView,结果是相同的。将其设置为带有CardView属性的LinearLayout的背景也没有任何效果。 - Yunyu L.
实际上,当在XML中使用android:foreground="?android:attr/selectableItemBackground"定义CardView时,仍然没有涟漪效果。 - Yunyu L.
我可以使用XML创建具有android:clickable="true"和selectableItemBackground前景的涟漪,但是我似乎无法在代码中重新创建它... - Yunyu L.
1个回答

9

结果发现我将Drawable的实例与多个cardview共享。通过使用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上获得了水波纹效果。

确认,setForeground()仅适用于API 23+ - Android文档错误地将其列为API Level 1。AOSP错误报告在此处 - https://code.google.com/p/android/issues/detail?id=186273。 - Sean Barbeau
这对我没有用。我尝试直接将其放在ImageView上,也尝试将其放在包含ImageView的FrameLayout上。两者都不起作用。 - Clive Jefferies
你需要在你的CardView上添加android:clickable="true"属性。 - Dagnogo Jean-François

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接