[android] 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.

This question is related to android android-5.0-lollipop android-cardview

The answer is


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

In JAVA

cardView.setCardBackgroundColor(0xFFFEFEFE);

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


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

You can use this in XML

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

or this in Java

cardView.setCardBackgroundColor(Color.WHITE);

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.


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 setBackgriundResource

 cv_add_goal_choose_color.setBackgroundResource(color)

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.


You can use this in java.

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

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


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

I used this code to set programmatically:

card.setCardBackgroundColor(color);

Or in XML you can use this code:

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

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


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

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 can use below

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

Simplest way for me is this one (Kotlin)

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

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


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.


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-5.0-lollipop

Android changing Floating Action Button color Android Support Design TabLayout: Gravity Center and Mode Scrollable Android statusbar icons color Notification bar icon turns white in Android 5 Lollipop How can I change default dialog button text color in android 5 Lollipop : draw behind statusBar with its color set to transparent Android lollipop change navigation bar color CardView not showing Shadow in Android L App crashing when trying to use RecyclerView on android 5.0 How to change status bar color to match app in Lollipop? [Android]

Examples related to android-cardview

CardView background color always white Margin between items in recycler view Android How to add colored border on cardview? How to add a recyclerView inside another recyclerView CardView Corner Radius CardView not showing Shadow in Android L RecyclerView inside ScrollView is not working Ripple effect on Android Lollipop CardView How do I get the position selected in a RecyclerView? Change the background color of CardView programmatically