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.
Styles and themes are declared in a style resource file in res/values/ , usually named styles. xml .
xml in the your application's res/values directory. Add a root <resources> node. For each style or theme, add a <style> element with a unique name and, optionally, a parent attribute. The name is used for referencing these styles later, and the parent indicates what style resource to inherit from.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With