简体   繁体   English

如何使用 style.xml 文件更改 MaterialCardView 的背景颜色?

[英]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.我想使用 style.xml 文件更改 MaterialCardView 的背景颜色。 It would really help with implementing "Dark mode"in my Android app.它真的有助于在我的 Android 应用程序中实现“暗模式”。

I have tried dynamically doing but would prefer this done using the theme.我尝试过动态执行,但更喜欢使用主题来完成。

Create your custom style for MaterialCardView that extends Widget.MaterialComponents.CardView:为扩展 Widget.MaterialComponents.CardView 的 MaterialCardView 创建自定义样式:

<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:然后您可以手动将此样式设置为 xml 布局中的单个 MaterialCardView:

<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):或者,您可以为自定义主题中的所有 MaterialCardViews 设置样式(从 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: Widget.MaterialComponents.CardView可以像任何其他组件一样设置样式:

<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.更改默认为#FFFFFF colorSurface ,对于深色主题可能相当有效。

see the documentation , which also explains how to apply it to all instances.请参阅文档,其中还说明了如何将其应用于所有实例。

Actually, I got it working by adding the attribute实际上,我通过添加属性使其工作

app:cardBackgroundColor="@color/colorAccent"

Of course, you have to define the app namespace, that goes by the following:当然,您必须定义 app 命名空间,如下所示:

xmlns:app="http://schemas.android.com/apk/res-auto"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM