如何使用 style.xml 文件更改 MaterialCardView 的背景颜色?
How to change the background colour for MaterialCardView using the style.xml file?
我想使用 style.xml 文件更改 MaterialCardView 的背景颜色。这真的有助于在我的 Android 应用程序中实施 "Dark mode"。
我试过动态地做,但更喜欢使用主题来完成。
Widget.MaterialComponents.CardView
可以像任何其他组件一样设置样式:
<style name="CustomCardView" parent="Widget.MaterialComponents.CardView">
<item name="cardBackgroundColor">?attr/colorSurface</item>
</style>
更改 colorSurface
,默认为 #FFFFFF
,对于深色主题可能相当有效。
请参阅 documentation,其中还说明了如何将其应用于所有实例。
为扩展 Widget.MaterialComponents.CardView:
的 MaterialCardView 创建自定义样式
<style name="YourCardView" parent="Widget.MaterialComponents.CardView">
<item name="cardBackgroundColor">@color/your_color</item>
</style>
然后您可以在 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>
或者您可以在自定义主题(从 MaterialComponents 扩展主题)中为所有 MaterialCardView 设置样式:
<style name="YourTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
<item name="materialCardViewStyle">@style/YourCardView</item>
</style>
实际上,我通过添加属性
让它工作
app:cardBackgroundColor="@color/colorAccent"
当然,您必须定义应用命名空间,如下所示:
xmlns:app="http://schemas.android.com/apk/res-auto"
我想使用 style.xml 文件更改 MaterialCardView 的背景颜色。这真的有助于在我的 Android 应用程序中实施 "Dark mode"。
我试过动态地做,但更喜欢使用主题来完成。
Widget.MaterialComponents.CardView
可以像任何其他组件一样设置样式:
<style name="CustomCardView" parent="Widget.MaterialComponents.CardView">
<item name="cardBackgroundColor">?attr/colorSurface</item>
</style>
更改 colorSurface
,默认为 #FFFFFF
,对于深色主题可能相当有效。
请参阅 documentation,其中还说明了如何将其应用于所有实例。
为扩展 Widget.MaterialComponents.CardView:
的 MaterialCardView 创建自定义样式<style name="YourCardView" parent="Widget.MaterialComponents.CardView">
<item name="cardBackgroundColor">@color/your_color</item>
</style>
然后您可以在 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>
或者您可以在自定义主题(从 MaterialComponents 扩展主题)中为所有 MaterialCardView 设置样式:
<style name="YourTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
<item name="materialCardViewStyle">@style/YourCardView</item>
</style>
实际上,我通过添加属性
让它工作app:cardBackgroundColor="@color/colorAccent"
当然,您必须定义应用命名空间,如下所示:
xmlns:app="http://schemas.android.com/apk/res-auto"