Search code examples
androidandroid-theme

How to change the background colour for MaterialCardView using the style.xml file?


I want to change the background colour for MaterialCardView using the style.xml file. It would really help with implementing "Dark mode"in my Android app.

I have tried dynamically doing but would prefer this done using the theme.


Solution

  • Create your custom style for MaterialCardView that extends Widget.MaterialComponents.CardView:

    <style name="YourCardView" parent="Widget.MaterialComponents.CardView">
        <item name="cardBackgroundColor">@color/your_color</item>
    </style>
    

    Then you can set this style manually to your single MaterialCardView in xml layout:

    <com.google.android.material.card.MaterialCardView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/YourCardView">
            <!-- card content -->
    </com.google.android.material.card.MaterialCardView>
    

    Or you can set the style for all MaterialCardViews within your custom theme (that extends a theme from MaterialComponents):

    <style name="YourTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
        <item name="materialCardViewStyle">@style/YourCardView</item>
    </style>