将 selectableItemBackground 添​​加到 CardView

Aur*_*tic 5 android android-xml android-cardview

我想将CardView的前景设置为?attr/selectableItemBackground.

当我在 xml 中声明前景时它起作用:

android:foreground="?attr/selectableItemBackground"
Run Code Online (Sandbox Code Playgroud)

但我想以编程方式设置前景。这不起作用:

int[] attrs = new int[]{R.attr.color_a, R.attr.selectableItemBackground};
TypedArray ta = context.obtainStyledAttributes(attrs);
mColorA = ta.getColor(0, 0);
mSelectableItemBackground = ContextCompat.getDrawable(context, ta.getResourceId(1, 0));
ta.recycle();

...

cardView.setOnClickListener(onClickListener);
cardView.setClickable(true);
cardView.setForeground(mSelectableItemBackground);
Run Code Online (Sandbox Code Playgroud)

但是,检索属性有效(mSelectableItemBackground 包含一个RippleDrawable),但是当我按下卡片时前景不会改变。

Aur*_*tic 2

问题是我将同一个 Drawable 与多张卡片一起使用。

您必须为每张卡检索一个新的可绘制对象。

更多详细信息请参阅此答案