Gabriele Mariotti Gabriele Mariotti - 5 months ago 109
Android Question

Change the background color of CardView programmatically

The CardView has an attribute

card_view:cardBackgroundColor
to define the background color.
This attribute works fine.

At the same time there isn't a method to change the color dynamically.

I've just tried solutions like:

mCardView.setBackgroundColor(...);


or using a Layout inside the cardView

<android.support.v7.widget.CardView>
<LinearLayout
android:id="@+id/inside_layout">
</android.support.v7.widget.CardView>

View insideLayout = mCardView.findViewById(R.id.inside_layout);
cardLayout.setBackgroundColor(XXXX);


These solutions don't work because the card has a cardCornerRadius.

Answer

What you are looking for is:

CardView card = ...
card.setCardBackgroundColor(color);