Kannan
Kannan

Reputation: 79

How to setStrokeColor for com.google.android.material.card.MaterialCardView programmatically

I tried the code below in my adapter class, but it is not working.

myViewHolder.cardview1.setStrokeColor(ContextCompat.getColor(context, R.color.selected_color));

Upvotes: 6

Views: 7391

Answers (2)

Gabriele Mariotti
Gabriele Mariotti

Reputation: 364868

Just use the setStrokeColor method:

MaterialCardView cardView = findViewById(R.id.card);
cardView.setStrokeColor(ContextCompat.getColor(this, R.color....));

You have to set the width of the stroke because the default value is 0dp.

<com.google.android.material.card.MaterialCardView
    android:id="@+id/card"
    app:strokeWidth="2dp"
    ..>

Otherwise use the setStrokeWidth method.

enter image description here

Upvotes: 4

Pillocron
Pillocron

Reputation: 161

I had the same problem, to solve it just add the invalidate() method:

myViewHolder.cardview1.setStrokeColor(ContextCompat.getColor(context, R.color.selected_color));
myViewHolder.cardview1.invalidate();

This updates the view.

Upvotes: 14

Related Questions