Search code examples
androidandroid-fragmentactivitytheme-daynight

Setting DayNight theme using AppCompatDelegate.setDefaultNightMode() not working for FragmentActivity


I'm a bit puzzled. I'm using a DayNight theme in my app (using AppCompatDelegate.setDefaultNightMode()), but can't get it to work in my MainActivity. The MainActivity (which extends FragmentActivity) looks like it's never set to dark theme - it always remains in light theme.

I tried setting the theme directly in my MainActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    super.onCreate(savedInstanceState);
    // create main activity.
}

But this is not working.

I have set all of the colors in my layout files properly using ?attr/colorReference. Does anyone know what is going wrong here?

EDIT: My styles.xml is as follows:

<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
    <!--Default typeface and colors:-->
    <item name="android:typeface">monospace</item>
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="colorAccentDarker">@color/colorAccentDarker</item>
    <item name="colorAccentDarker_80percent">@color/colorAccentDarker_80percent</item>

    <!--Show people's own wallpaper background-->
    <item name="android:windowShowWallpaper">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
</style>

Solution

  • MainActivity (which extends FragmentActivity)

    FragmentActivity has no idea of AppCompat. AppCompatDelegate is only used by AppCompatActivity or you have to wire it manually to your other activities.

    You can extend AppCompatActivity instead of FragmentActivity.