将自定义CardView样式附加到主题 [英] Attach custom CardView style to theme
问题描述
在我的应用中,我有两个主题(浅色和深色),我希望所有CardView
都可以根据选择的主题来更改其背景颜色.
In my app, I have two themes (light and dark), and I want all of my CardView
s to change their background color depending on which theme is selected.
我不想要想要的是:
<android.support.v7.widget.CardView
style="@style/CardView.MyBlue"
android:layout_width="200dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal">
上面的代码不是动态的.我需要根据选择的是浅色还是深色主题自动应用两种样式.
The above code is not dynamic. I need my two styles to automatically be applied depending on if a light or a dark theme is selected.
我现在所拥有的不起作用:
What I have right now doesn't work:
<style name="AppTheme.Light" parent="Theme.AppCompat.Light">
...
<item name="cardViewStyle">@style/CardViewStyle.Light</item>
</style>
<style name="AppTheme.Dark" parent="Theme.AppCompat">
...
<item name="cardViewStyle">@style/CardViewStyle.Dark</item>
</style>
<style name="CardViewStyle.Light" parent="CardView">
<item name="cardBackgroundColor">@color/cardview_dark_background</item>
</style>
<style name="CardViewStyle.Dark" parent="CardView">
<item name="cardBackgroundColor">@color/cardview_light_background</item>
</style>
我读到某个地方,您可以在/res/values/
中定义一个styleable.xml
文件以键入单词cardViewStyle
,因此我做到了:
I read somewhere that you can define a styleable.xml
file in /res/values/
to key the word cardViewStyle
, so I did that:
styleable.xml:
<resources>
<declare-styleable name="AppTheme">
<attr name="cardViewStyle" format="reference" />
</declare-styleable>
</resources>
更新
类似的问题此处,也没有答案.
Update
Similar question here with no answer either.
推荐答案
在styles.xml中
In styles.xml
<resources>
<attr format="reference" name="cardStyle"/>
<style name="Light" parent="Theme.AppCompat.NoActionBar">
<item name="cardStyle">@style/CardView.Light</item>
...
</style>
<style name="Dark" parent="Theme.AppCompat.NoActionBar">
<item name="cardStyle">@style/CardView.Dark</item>
...
</style>
</resources>
然后在其他xml中使用new属性,您将像这样使用它
Then in your other xml to use the new attribute, you would use it like this
style="?attr/cardStyle"
这篇关于将自定义CardView样式附加到主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!