Android AppCompatDelegate.setDefaultNightMode not recreating parent activity in android 9

4k views Asked by At

Hello I am using this AppCompatDelegate to change between day/night themes I have 2 activities A& B this code called from activity B it should recreating activity B & A with the chosen style here is my code

  applyNight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
      if (!isNight) {

            SharedPrefrencesMethods.savePreferences(this, getString(R.string.night_key), true);

            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);


        } else {
            SharedPrefrencesMethods.savePreferences(this, getString(R.string.night_key), false);

            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

        }
            }
        });

I tested it on android 7 & 6 it's working fine i.e when changing mode in activity B and press back activity A recreating with the new theme. When trying it on android 9 it's changing the activity B only and not affecting it's parent activity A.

1

There are 1 answers

0
Tané Tachyon On

I was having that problem too, and then took the advice of Chris Banes in Google's official Android Developers blog https://medium.com/androiddevelopers/appcompat-v23-2-daynight-d10f90c83e94 to set setDefaultNightMode in the app's application class in the first place, so I created a class EcwgApplication extending Application as he shows, and added android:name=".EcwgApplication" in the application section of the manifest. I also put my method for switching themes in the application class as well, that my settings activity can call when the user changes the theme setting (in addition to updating SharedPreferences with the change before calling it), so it looks like this:

public class EcwgApplication extends Application {
    public void onCreate() {
        super.onCreate();

        int selectedDarkLightTheme = PreferenceManager.getDefaultSharedPreferences(this).getInt(getString(R.string.preferences_dark_light_mode_selected_key), AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
        AppCompatDelegate.setDefaultNightMode(selectedDarkLightTheme);
    }

    public static void setDarkLightTheme(int selectedDarkLightTheme) {
        AppCompatDelegate.setDefaultNightMode(selectedDarkLightTheme);
    }
}

This worked fine with Android OS versions 24 through 29, but with 21 (the lowest version this app is supporting) through 23 I would get a black screen on returning to the first activity, and while rotating the screen would fix that, it also made clear that UI state was not being saved. So I changed the StartActivity for the Settings screen to StartActivityForResult, and in onActivityResult, check if the version number <= 23, and if so, do this.recreate().

I need to keep doing more testing, but at least so far everything seems to be working great.