Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add selectableItemBackground to CardView

I want to set the foreground of my CardView to ?attr/selectableItemBackground.

It work's when I declare the foreground in xml:

android:foreground="?attr/selectableItemBackground"

But I want to set the foreground programmatically. This doesn't work:

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

However, retrieving the attributes works (mSelectableItemBackground contains a RippleDrawable), but the foreground doesn't change when I press on the Card.

like image 247
Auroratic Avatar asked Oct 31 '22 15:10

Auroratic


1 Answers

The issue was that I used the same Drawable with multiple Cards.

You have to retrieve a new Drawable for each Card.

More details in this answer.

like image 137
Auroratic Avatar answered Nov 11 '22 09:11

Auroratic