159

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.

Paul Burke
  • 25,496
  • 9
  • 66
  • 62
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841

27 Answers27

314

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"
Ujjwal Jung Thapa
  • 604
  • 2
  • 8
  • 31
Simon
  • 13,173
  • 14
  • 66
  • 90
116

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"
    >
user790999
  • 1,414
  • 3
  • 11
  • 9
  • 2
    The OP tell us about that property in the first line of his question, he said he wants to achieve it "dinamically". – stramin May 28 '19 at 15:15
33

You can use this in XML

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

or this in Java

cardView.setCardBackgroundColor(Color.WHITE);
eluleci
  • 3,489
  • 1
  • 26
  • 24
21

I used this code to set programmatically:

card.setCardBackgroundColor(color);

Or in XML you can use this code:

card_view:cardBackgroundColor="@android:color/white"
m.v.n.kalyani
  • 760
  • 7
  • 20
16

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.

Steve
  • 225
  • 2
  • 8
12

You can use below

cardview.setBackgroundColor(Color.parseColor("#EAEDED"));
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Aditya Patil
  • 1,287
  • 12
  • 19
10

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.

Paul Burke
  • 25,496
  • 9
  • 66
  • 62
8

A little late here & partially off topic since this is not programmatically but I find it best to setup styles for Widgets and you can do this for a CardView just create a style it will keep your xml cleaner...

<style name="MyCardViewStyle" parent="CardView">
    <!-- Card background color -->
    <item name="cardBackgroundColor">@android:color/white</item>
    <!-- Ripple for API 21 of android, and regular selector on older -->
    <item name="android:foreground">?android:selectableItemBackground</item>
    <!-- Resting Elevation from Material guidelines -->
    <item name="cardElevation">2dp</item>
    <!-- Add corner Radius -->
    <item name="cardCornerRadius">2dp</item>
    <item name="android:clickable">true</item>
    <item name="android:layout_margin">8dp</item>
</style>

this is using android.support.v7.widget.CardView

and then setting the style in the layout file:

 <?xml version="1.0" encoding="utf-8"?>
 <android.support.v7.widget.CardView
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_height="wrap_content"
     android:layout_width="match_parent"
     style="@style/MyCardViewStyle">
    <!-- Other fields-->
 </android.support.v7.widget.CardView>

you need to import the appcompat-v7 library using Android studio via gradle:

 dependencies {
     compile 'com.android.support:appcompat-v7:22.2.0'
 }

hope this helps. happy coding

kandroidj
  • 13,784
  • 5
  • 64
  • 76
  • 1
    Thanks for pointing out the XML styling. Always struggling with that. Isn't there a way to define the style in themes.xml? Then you wouldn't have to set the style for each CardView. – Wirling Jan 13 '16 at 10:31
  • That is pretty awesome - I was struggling with trying to figure out how to propagate selectors down through the layout - and this was NOT working pre API21. The ripple was working fine post API21- but your theme approach was the first time I managed to get the CardView to give the right look on clicking across the contents. – Jim Andreas Nov 17 '16 at 11:50
  • The OP tell us about that property in the first line of his question, he said he wants to achieve it "dinamically". – stramin May 28 '19 at 15:17
6

It is very simple in kotlin. Use ColorStateList to change card view colour

   var color = R.color.green;
   cardView.setCardBackgroundColor(context.colorList(color));

A kotlin extension of ColorStateList:

fun Context.colorList(id: Int): ColorStateList {
    return ColorStateList.valueOf(ContextCompat.getColor(this, id))
}
Mohsen Mousavi
  • 131
  • 2
  • 8
Deepak Ror
  • 333
  • 1
  • 5
  • 13
4

Simplest way for me is this one (Kotlin)

card_item.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#fc4041"))
Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77
4

In Kotlin, I was able to change the background color like this:

var card: CardView = itemView.findViewById(com.mullr.neurd.R.id.learn_def_card)
card.setCardBackgroundColor(ContextCompat.getColor(main,R.color.selected))

Then if you want to remove the color, you can do this:

card.setCardBackgroundColor(Color.TRANSPARENT)

Using this method I was able to create a selection animation.
https://gfycat.com/equalcarefreekitten

Code on the Rocks
  • 11,488
  • 3
  • 53
  • 61
3

In JAVA

cardView.setCardBackgroundColor(0xFFFEFEFE);

android use ARGB colors. you can use like this (0xFF + RGB COLOR)--Hard-coded color.

Narendra Baratam
  • 828
  • 1
  • 12
  • 26
yakup_y
  • 155
  • 2
  • 7
2

I came across the same issue while trying to create a cardview programmatically, what is strange is that looking at the doc https://developer.android.com/reference/android/support/v7/widget/CardView.html#setCardBackgroundColor%28int%29, Google guys made public the api to change the background color of a card view but weirdly i didn't succeed to have access to it in the support library, so here is what worked for me:

CardViewBuilder.java

    mBaseLayout = new FrameLayout(context);
    // FrameLayout Params
    FrameLayout.LayoutParams baseLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    mBaseLayout.setLayoutParams(baseLayoutParams);

    // Create the card view.
    mCardview = new CardView(context);
    mCardview.setCardElevation(4f);
    mCardview.setRadius(8f);
    mCardview.setPreventCornerOverlap(true); // The default value for that attribute is by default TRUE, but i reset it to true to make it clear for you guys
    CardView.LayoutParams cardLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    cardLayoutParams.setMargins(12, 0, 12, 0);
    mCardview.setLayoutParams(cardLayoutParams);
    // Add the card view to the BaseLayout
    mBaseLayout.addView(mCardview);

    // Create a child view for the cardView that match it's parent size both vertically and horizontally
    // Here i create a horizontal linearlayout, you can instantiate the view of your choice
    mFilterContainer = new LinearLayout(context);
    mFilterContainer.setOrientation(LinearLayout.HORIZONTAL);
    mFilterContainer.setPadding(8, 8, 8, 8);
    mFilterContainer.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT, Gravity.CENTER));

    // And here is the magic to get everything working
    // I create a background drawable for this view that have the required background color
    // and match the rounded radius of the cardview to have it fit in.
    mFilterContainer.setBackgroundResource(R.drawable.filter_container_background);

    // Add the horizontal linearlayout to the cardview.
    mCardview.addView(mFilterContainer);

filter_container_background.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="8dp"/>
<solid android:color="@android:color/white"/>

Doing that i succeed in keeping the cardview shadow and rounded corners.

  • You are adding a LL in your cardview in this way and of course you can do it, but it doesn't answer the original question. – Gabriele Mariotti Nov 27 '14 at 17:57
  • The request was about changing the card background color dynamically, and i think this method does it pretty simply by changing the inner layout background color. Or am i missing something. – Martial Konvi Nov 27 '14 at 18:05
2

I have got the same problem on Xamarin.Android - VS (2017)

The Solution that worked for me:

SOLUTION

In your XML file add:

 xmlns:card_view="http://schemas.android.com/apk/res-auto"

and in your android.support.v7.widget.CardView element add this propriety:

card_view:cardBackgroundColor="#ffb4b4"

(i.e.)

<android.support.v7.widget.CardView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_margin="12dp"
    card_view:cardCornerRadius="4dp"
    card_view:cardElevation="1dp"
    card_view:cardPreventCornerOverlap="false"
    card_view:cardBackgroundColor="#ffb4b4" />

You can also add cardElevation and cardElevation.

If you want to edit the cardview programmatically you just need to use this code: For (C#)

    cvBianca = FindViewById<Android.Support.V7.Widget.CardView>(Resource.Id.cv_bianca);
    cvBianca.Elevation = 14;
    cvBianca.Radius = 14;
    cvBianca.PreventCornerOverlap = true;
    cvBianca.SetCardBackgroundColor(Color.Red);

And now you can change background color programmatically without lost border, corner radius and elevation.

Fabio
  • 593
  • 3
  • 14
1

You can use this in java.

cardView.setCardBackgroundColor(Color.parseColor("#cac8a0"));

code color form http://www.color-hex.com/

Muthu Krishnan
  • 196
  • 1
  • 10
1

I finally got the corners to stay. This is c#, Xamarin.Android

in ViewHolder:

CardView = itemView.FindViewById<CardView>(Resource.Id.cdvTaskList);

In Adapter:

vh.CardView.SetCardBackgroundColor(Color.ParseColor("#4dd0e1"));
1

You can use this in XML

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

or by programmatically

cardView.setCardBackgroundColor(ContextCompat.getColor(this, R.color.my_color));
Mujahid Khan
  • 1,712
  • 1
  • 18
  • 24
1

If you wanna change card tint color just try this code it works for me. For me this code works. I use it with card and image views but i thins it works in any view to change their tints colors. cardBookmark is my cardView name.

var cardDrawable: Drawable = binding.cardBookmark.background
cardDrawable = DrawableCompat.wrap(cardDrawable)
DrawableCompat.setTint(cardDrawable, resources.getColor(R.color.shuffleColor))
binding.cardBookmark.background = cardDrawable
Anorov Hasan
  • 123
  • 2
  • 2
1

Is some cases its going to be a little tricky becase not all the time the code cardview.setBackgroundColor(R.color.red) is going to work.

I solved my problem this way..

final color = ColorStateList.valueOf(context.getResources().getColor(R.color.light_tab_selected));
userNoteTabCardView.setBackgroundTintList(color);
StackOverflower
  • 369
  • 2
  • 12
1

in the activity of fragment do this to get the color in values/color

  cardView.setCardBackgroundColor(Color.alpha(R.color.gray999ea4));
FEELIX
  • 407
  • 4
  • 8
0

Cardview is a bit coy. I had list of colors in my structure and Model is like

class ModelColor : Serializable {

var id: Int? = 0
var title: String? = ""
var color: Int? = 0// HERE IS THE COLOR FIELD WE WILL USE

constructor(id: Int?, title: String?, color: Int?) {
    this.id = id
    this.title = title
    this.color = color
}

}

load the model with color, last item on constructure taking from R.color

 list.add(ModelColor(2, getString(R.string.orange), R.color.orange_500))

and finaly you can setBackgrıundResource

 cv_add_goal_choose_color.setBackgroundResource(color)
Samir
  • 6,405
  • 5
  • 39
  • 42
0

You only need to set card background color.

yourCard.setCardBackgroundColor(Color.WHITE);
Rbzium
  • 9
  • 1
0

One sufficient way to change the background color for cardView is setBackgroundResource, You can create drawable file as well and pass to setBackgroundResource,

holder.cardView.setBackgroundResource(R.drawable.white_frame)

or

holder.cardView.setBackgroundResource(R.color.white)

Sam Sh
  • 1
  • 1
0
private MaterialCardView imgIgnition;
imgIgnition = findViewById(R.id.imgIgnition);
imgIgnition.setCardBackgroundColor(Color.parseColor("#198754"));

THE Above Code Worked For Mee

Aaraf Rao
  • 19
  • 1
  • 4
0

app:cardBackgroundColor="" in xml

oneday
  • 1
  • 2
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Zahra Oct 22 '22 at 11:09
-1

try it works easy

<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    card_view:cardBackgroundColor="#fff"
    card_view:cardCornerRadius="9dp"
    card_view:cardElevation="4dp"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingTop="10dp"
    android:paddingBottom="10dp">
Vishal Vaishnav
  • 3,346
  • 3
  • 26
  • 57
  • 1
    The OP tell us about that property in the first line of his question, he said he wants to achieve it programmatically/dinamically. – stramin May 28 '19 at 15:19
-1
CardView cardView;

cardView.setCardBackgroundColor(getResources().getColor(R.color.colorPrimary));