![](/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.