Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the background color of CardView programmatically

What you are looking for is:

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

In XML

 card_view:cardBackgroundColor="@android:color/white"

Update: in XML

app:cardBackgroundColor="@android:color/white"

Use the property card_view:cardBackgroundColor:

<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="fill_parent"
    android:layout_height="150dp"
    android:layout_gravity="center"
    card_view:cardCornerRadius="4dp"
    android:layout_margin="10dp"
    card_view:cardBackgroundColor="#fff"
    >

You can use this in XML

card_view:cardBackgroundColor="@android:color/white"

or this in Java

cardView.setCardBackgroundColor(Color.WHITE);

I used this code to set programmatically:

card.setCardBackgroundColor(color);

Or in XML you can use this code:

card_view:cardBackgroundColor="@android:color/white"

I was having a similar issue with formatting CardViews in a recylerView.

I got this simple solution working, not sure if it's the best solution, but it worked for me.

mv_cardView.getBackground().setTint(Color.BLUE)

It gets the background Drawable of the cardView and tints it.


The way it's set in the initialize method uses the protected RoundRectDrawable class, like so:

RoundRectDrawable backgroundDrawable = new RoundRectDrawable(backgroundColor, cardView.getRadius());
cardView.setBackgroundDrawable(backgroundDrawable);

It's not pretty, but you can extend that class. Something like:

package android.support.v7.widget;

public class MyRoundRectDrawable extends RoundRectDrawable {

    public MyRoundRectDrawable(int backgroundColor, float radius) {
        super(backgroundColor, radius);
    }

}

then:

final MyRoundRectDrawable backgroundDrawable = new MyRoundRectDrawable(bgColor,
            mCardView.getRadius());
mCardView.setBackgroundDrawable(backgroundDrawable);

EDIT

This won't give you the shadow on < API 21, so you'd have to do the same with RoundRectDrawableWithShadow.

There doesn't appear to be a better way to do this.


You can use below

cardview.setBackgroundColor(Color.parseColor("#EAEDED"));