我想为我的android应用实现夜间模式,因此我已使用Theme.AppCompat.DayNight主题实施夜间模式。但是我必须在夜间模式下自定义工具栏和回收站视图的颜色。
为此,我已经在attrs.xml文件中声明了该属性,并将该属性用作recyclerview中的背景。
这是attrs.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ds">
<attr name="rv_color" format="color"/>
</declare-styleable>
</resources>
这里是回收站视图
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?attr/rv_color"
android:overScrollMode="never"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
现在为样式,我已经为Night Mode声明了styles.xml和styles.xml(夜晚)。
这是styles.xml
<style name="AppTheme" parent="Theme.AppCompat.DayNight">
<!-- Customize your theme here. -->
<item name="colorPrimary">@android:color/white</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="android:textColorPrimary">@color/colorPrimary</item>
<item name="android:windowDisablePreview">false</item>
<item name="rv_color">#FF0000</item>
</style>
这是styles.xml(晚上)
<style name="AppTheme" parent="Theme.AppCompat.DayNight">
<!-- Customize your theme here. -->
<item name="colorPrimary">@android:color/white</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="android:textColorPrimary">@color/colorPrimary</item>
<item name="android:windowDisablePreview">false</item>
<item name="rv_color">#FFFF00</item>
</style>
在styles.xml文件中,我为recyclerview背景定义了红色,在夜间模式文件中定义了黄色。
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
以上行出现在夜间模式的活动文件中。
但是每次回收器视图的颜色都是红色的,即来自styles.xml
为什么styles.xml(夜间)颜色不适用于recyclerview。
为什么不起作用?或其他任何方式?
另一种方法是在资源中创建一个values-night文件夹,在其中放置colors.xml并声明一个类似于“ rv_color”的颜色:
<color name="rv_color">#ffff00</color>
以及常规值/colors.xml:
<color name="rv_color">#ff0000</color>
将您的回收站视图的颜色设置为该颜色。无需声明任何自定义属性。