I want to implement night mode for my android app so I have used Theme.AppCompat.DayNight theme for implementing Night Mode. But I have to customize the color of the Toolbar and recycler view during the Night Mode.
For that, I have declared the attribute in the attrs.xml file and use that attribute as a background in the recyclerview.
Here is the attrs.xml file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ds">
<attr name="rv_color" format="color"/>
</declare-styleable>
</resources>
Here is the recyclerview
<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">
Now for styles, I have declared styles.xml and styles.xml (night) for Night Mode.
Here is the 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>
Here is the styles.xml (night)
<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>
In the styles.xml file I have defined RED color for recyclerview background and YELLOW color in the night mode file.
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
The above line is present in the Activity file which to Night Mode.
But Every time the recycler view color is RED i.e. from the styles.xml
Why styles.xml (night) color is not applying to the recyclerview.
Why it is not working? or any other way to do this?
I had the same problem (only that the RecyclerView always had the color defined in styles.xml (night), regardless of whether day or night mode was activated) and found a solution in this thread; the only thing I had to change was not to call
but to use
instead when creating the Adapter with
in the corresponding Activity. Working solution: