在我的应用中,我有两个主题(浅色和深色),并且我希望所有CardView
s可以根据选择的主题来更改其背景颜色。
我不想要的是:
<android.support.v7.widget.CardView
style="@style/CardView.MyBlue"
android:layout_width="200dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal">
上面的代码不是动态的。我需要根据选择浅色主题还是深色主题来自动应用两种样式。
我现在所拥有的不起作用:
<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>
我读过某个地方,您可以在其中定义一个styleable.xml
文件/res/values/
以输入单词cardViewStyle
,因此我做到了:
styleable.xml:
<resources>
<declare-styleable name="AppTheme">
<attr name="cardViewStyle" format="reference" />
</declare-styleable>
</resources>
类似的问题在这里也没有答案。
在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属性,您将像这样使用它
style="?attr/cardStyle"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句