Search code examples
androidandroid-5.0-lollipopandroid-cardview

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.


Solution

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