How to change the background colour for MaterialCardView using the style.xml file?
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>
Widget.MaterialComponents.CardView
can be styled just alike any other component:
<style name="CustomCardView" parent="Widget.MaterialComponents.CardView">
<item name="cardBackgroundColor">?attr/colorSurface</item>
</style>
Changing colorSurface
, which defaults to #FFFFFF
, might be rather effective for a dark theme.
see the documentation, which also explains how to apply it to all instances.