【发布时间】:2019-03-23 04:57:10
【问题描述】:
我想使用 style.xml 文件更改 MaterialCardView 的背景颜色。这对在我的 Android 应用中实现“暗模式”很有帮助。
我尝试过动态执行,但更喜欢使用主题来完成。
【问题讨论】:
标签: android android-theme
我想使用 style.xml 文件更改 MaterialCardView 的背景颜色。这对在我的 Android 应用中实现“暗模式”很有帮助。
我尝试过动态执行,但更喜欢使用主题来完成。
【问题讨论】:
标签: android android-theme
为扩展 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 扩展主题)中为所有 MaterialCardViews 设置样式:
<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"
【讨论】:
Widget.MaterialComponents.CardView 可以像任何其他组件一样设置样式:
<style name="CustomCardView" parent="Widget.MaterialComponents.CardView">
<item name="cardBackgroundColor">?attr/colorSurface</item>
</style>
更改colorSurface(默认为#FFFFFF)对于深色主题可能相当有效。
请参阅documentation,其中还说明了如何将其应用于所有实例。
【讨论】: