Change the background color of CardView programmatically

AndroidAndroid 5.0-LollipopAndroid Cardview

Android Problem Overview


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.

Android Solutions


Solution 1 - Android

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"

Solution 2 - Android

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"
    >

Solution 3 - Android

You can use this in XML

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

or this in Java

cardView.setCardBackgroundColor(Color.WHITE);

Solution 4 - Android

I used this code to set programmatically:

card.setCardBackgroundColor(color);

Or in XML you can use this code:

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

Solution 5 - Android

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.

Solution 6 - Android

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.

Solution 7 - Android

You can use below

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

Solution 8 - Android

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

Solution 9 - Android

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

Solution 10 - Android

In JAVA

cardView.setCardBackgroundColor(0xFFFEFEFE);

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

Solution 11 - Android

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

Solution 12 - Android

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.

Solution 13 - Android

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.

Solution 14 - Android

You can use this in java.

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

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

Solution 15 - Android

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

Solution 16 - Android

Simplest way for me is this one (Kotlin)

card_item.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#fc4041"))

Solution 17 - Android

You can use this in XML

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

or by programmatically

cardView.setCardBackgroundColor(ContextCompat.getColor(this, R.color.my_color));

Solution 18 - Android

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)

Solution 19 - Android

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

Solution 20 - Android

> 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">

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGabriele MariottiView Question on Stackoverflow
Solution 1 - AndroidSimonView Answer on Stackoverflow
Solution 2 - Androiduser790999View Answer on Stackoverflow
Solution 3 - AndroideluleciView Answer on Stackoverflow
Solution 4 - Androidm.v.n.kalyaniView Answer on Stackoverflow
Solution 5 - AndroidSteve View Answer on Stackoverflow
Solution 6 - AndroidPaul BurkeView Answer on Stackoverflow
Solution 7 - AndroidAditya PatilView Answer on Stackoverflow
Solution 8 - AndroidkandroidjView Answer on Stackoverflow
Solution 9 - AndroidDeepak RorView Answer on Stackoverflow
Solution 10 - Androidyakup_yView Answer on Stackoverflow
Solution 11 - AndroidJoe MullerView Answer on Stackoverflow
Solution 12 - AndroidMartial KonviView Answer on Stackoverflow
Solution 13 - AndroidFabioView Answer on Stackoverflow
Solution 14 - AndroidMuthu KrishnanView Answer on Stackoverflow
Solution 15 - AndroidCheradenine ZakalweView Answer on Stackoverflow
Solution 16 - AndroidGastón SaillénView Answer on Stackoverflow
Solution 17 - AndroidMujahid KhanView Answer on Stackoverflow
Solution 18 - AndroidSamirView Answer on Stackoverflow
Solution 19 - AndroidAnorov HasanView Answer on Stackoverflow
Solution 20 - AndroidSingupurapu prudhvi rajView Answer on Stackoverflow