android - 将 selectableItemBackground 添​​加到 CardView

标签 android android-xml android-cardview

我想设置我的 CardView 的前景到 ?attr/selectableItemBackground

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

android:foreground="?attr/selectableItemBackground"

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

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

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

最佳答案

问题是我对多张卡片使用了同一个 Drawable。

您必须为每张卡片检索一个新的 Drawable。

更多详情请参见 this answer .

关于android - 将 selectableItemBackground 添​​加到 CardView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33703844/

相关文章:

android - 在网格中添加 OxyPlot View

android - Eclipse 设备选择器

android - 您能告诉我以下订阅示例有什么问题吗?

android - 在 android.support.v7.widget.GridLayout 中使用 <include> 显示不正确

android - 类似工具的行为 :text in a custom view?

android - Pre-Lollipop 上的 CardView 兼容性问题

java - Android 11 : Primary directory (invalid) not allowed for content://media/external/file allowed directories are [Download, 文档]

android - 在 Android 上创建多个 preferences.xml 文件时如何重用代码?

android - Material cardView 子元素的背景色

android - 动态改变 CardView 的背景颜色