3

我想为我的 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">

现在对于样式,我已经为夜间模式声明了 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。

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

4

3 回答 3

7

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

getApplicationContext() 

但要使用

MyActivity.this 

而是在创建适配器时使用

MyAdapter adapter = new MyAdapter(getApplicationContext(), arrayList);

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

MyAdapter adapter = new MyAdapter(MyActivity.this, arrayList);
于 2020-03-23T18:40:26.237 回答
3

另一种方法是在您的资源中创建一个 values-night 文件夹,在其中放置一个 colors.xml 并声明一个颜色,如“rv_color”:

<color name="rv_color">#ffff00</color>

在常规值/colors.xml 中:

<color name="rv_color">#ff0000</color>

将 recyclerview 的颜色设置为该颜色。无需声明任何自定义属性。

于 2019-10-21T07:34:46.673 回答
0

当我第一次尝试实施 ondzilla 的建议时,它不起作用。但是,当我将 recyclerview 背景设置为 color.xml 文件中已有的另一种颜色时,背景现在可以在白天/黑夜之间正确切换。然后我将它切换回 rv_color 并且它工作正常。

不知道这是否对你有帮助,但我很高兴你问了这个问题,我的现在可以工作了。

于 2019-11-07T16:41:02.537 回答