Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 320
Vyom Maitreya Avatar asked Mar 23 '19 04:03

Vyom Maitreya


People also ask

Where is style XML in Android Studio?

Styles and themes are declared in a style resource file in res/values/ , usually named styles. xml .

How to create style XML file in Android Studio?

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.


1 Answers

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>
like image 126
Oleksandr Shapoval Avatar answered Sep 20 '22 16:09

Oleksandr Shapoval