夜间模式颜色不适用于回收站视图背景

Roh*_*har 2 android android-styles android-recyclerview android-night-mode android-dark-theme

我想为我的 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>
Run Code Online (Sandbox Code Playgroud)

这是回收站视图

 <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">
Run Code Online (Sandbox Code Playgroud)

现在对于样式,我已经为夜间模式声明了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>
Run Code Online (Sandbox Code Playgroud)

这是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>
Run Code Online (Sandbox Code Playgroud)

在styles.xml 文件中,我为recyclerview 背景定义了红色,在夜间模式文件中定义了黄色。

AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
Run Code Online (Sandbox Code Playgroud)

上面一行出现在夜间模式的活动文件中。

但是每次回收器视图颜色都是红色的,即来自styles.xml

为什么styles.xml(夜间)颜色不适用于recyclerview。

为什么它不起作用?或任何其他方式来做到这一点?

小智 6

我遇到了同样的问题(只是 RecyclerView 始终具有在styles.xml(夜间)中定义的颜色,无论白天还是夜间模式被激活)并在此线程中找到了解决方案;我唯一需要改变的就是不要打电话

getApplicationContext() 
Run Code Online (Sandbox Code Playgroud)

但要使用

MyActivity.this 
Run Code Online (Sandbox Code Playgroud)

而是在创建适配器时

MyAdapter adapter = new MyAdapter(getApplicationContext(), arrayList);
Run Code Online (Sandbox Code Playgroud)

在相应的活动中。工作解决方案:

MyAdapter adapter = new MyAdapter(MyActivity.this, arrayList);
Run Code Online (Sandbox Code Playgroud)