Android going back to parent activity after setdefaultnightmode

  android, android-studio, theme-daynight

I have an android application which uses material daynight theme.

My App has the follow heirarchy:

MainActivity->Activity A-> Activity B.(MainActivity creates A which creates B)

Both Activity A and Activity B(not MainActivity) extend a BaseActivity which handles menuitem clicks.

When the user is in Activity B and he changes the theme (option available as menu item), the app automatically switches to Activity A.Why is this happening?

Expected Behaviour after theme change: Stay in current activity even if it has to be recreated.

Actual Behaviour after theme change: Switches to parent activity.

Code in Application class to initialize app theme on start:

        int theme=settingsPreferences.getInt("theme",-2); //-2 is not found
        if(theme==-2)
        {
            theme= AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM;
            settingsPreferencesEditor.putInt("theme",theme);
            settingsPreferencesEditor.commit();
        }
        AppCompatDelegate.setDefaultNightMode(theme);

Code in BaseActivity(extended by Activity A and B) to handle theme change on radio click:

public boolean onOptionsItemSelected(MenuItem menuItem){
switch (menuItem.getItemId()){
case R.id.lightTheme:
                menuItem.setChecked(true);
                settingsPreferencesEditor.putInt("theme",AppCompatDelegate.MODE_NIGHT_NO);
                settingsPreferencesEditor.commit();
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                return true;
            case R.id.darkTheme:
                menuItem.setChecked(true);
                settingsPreferencesEditor.putInt("theme",AppCompatDelegate.MODE_NIGHT_YES);
                settingsPreferencesEditor.commit();
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                return true;
            case R.id.systemDefaultTheme:
                menuItem.setChecked(true);
                settingsPreferencesEditor.putInt("theme",AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
                settingsPreferencesEditor.commit();
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
                return true;
            default:
                return false;
        }
        return super.onOptionsItemSelected(menuItem);

Thanks to everyone trying to help 🙂

Source: Android Questions

LEAVE A COMMENT