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

Vyo*_*eya 7 android android-theme

我想使用 style.xml 文件更改 MaterialCardView 的背景颜色。它真的有助于在我的 Android 应用程序中实现“暗模式”。

我尝试过动态执行,但更喜欢使用主题来完成。

小智 11

为扩展 Widget.MaterialComponents.CardView 的 MaterialCardView 创建自定义样式:

<style name="YourCardView" parent="Widget.MaterialComponents.CardView">
    <item name="cardBackgroundColor">@color/your_color</item>
</style>
Run Code Online (Sandbox Code Playgroud)

然后您可以手动将此样式设置为 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>
Run Code Online (Sandbox Code Playgroud)

或者,您可以为自定义主题中的所有 MaterialCardViews 设置样式(从 MaterialComponents 扩展主题):

<style name="YourTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="materialCardViewStyle">@style/YourCardView</item>
</style>
Run Code Online (Sandbox Code Playgroud)


Mar*_*ler 5

Widget.MaterialComponents.CardView 可以像任何其他组件一样设置样式:

<style name="CustomCardView" parent="Widget.MaterialComponents.CardView">
    <item name="cardBackgroundColor">?attr/colorSurface</item>
</style>
Run Code Online (Sandbox Code Playgroud)

改变 colorSurface,默认为#FFFFFF,对于深色主题可能相当有效。

请参阅文档,其中还说明了如何将其应用于所有实例。


rom*_*eso 5

实际上,我通过添加属性使其工作

app:cardBackgroundColor="@color/colorAccent"
Run Code Online (Sandbox Code Playgroud)

当然,您必须定义 app 命名空间,如下所示:

xmlns:app="http://schemas.android.com/apk/res-auto"
Run Code Online (Sandbox Code Playgroud)