![](/img/trans.png)
[英]change the background of actionbar from java code as defined in the style.xml
[英]How to change the background colour for MaterialCardView using the style.xml file?
我想使用 style.xml 文件更改 MaterialCardView 的背景颜色。 它真的有助于在我的 Android 应用程序中实现“暗模式”。
我尝试过动态执行,但更喜欢使用主题来完成。
为扩展 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>
或者,您可以为自定义主题中的所有 MaterialCardViews 设置样式(从 MaterialComponents 扩展主题):
<style name="YourTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
<item name="materialCardViewStyle">@style/YourCardView</item>
</style>
Widget.MaterialComponents.CardView
可以像任何其他组件一样设置样式:
<style name="CustomCardView" parent="Widget.MaterialComponents.CardView">
<item name="cardBackgroundColor">?attr/colorSurface</item>
</style>
更改默认为#FFFFFF
colorSurface
,对于深色主题可能相当有效。
请参阅文档,其中还说明了如何将其应用于所有实例。
实际上,我通过添加属性使其工作
app:cardBackgroundColor="@color/colorAccent"
当然,您必须定义 app 命名空间,如下所示:
xmlns:app="http://schemas.android.com/apk/res-auto"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.