Change theme without activity restart

I’m having trouble change app theme without activity restart.
The project structure is like 1 main Activity and 5 Fragments inside it with bottomNavigationView; theme change toggle is in setting Fragment and other fragments contain list of data with different view types.

styles.xml

<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowBackground">@null</item>
    <item name="android:windowDisablePreview">true</item>
    <item name="android:ambientShadowAlpha">0.1</item>
    <item name="android:spotShadowAlpha">0.1</item>
</style>

I call setDarkLightTheme method on Application class to change theme on every toggle

public class MyApp extends Application {

private static MyApp singleton = null;

public synchronized static MyApp getInstance() {
    if (singleton == null) {
        singleton = new MyApp();
    }
    return singleton;
}

@Override
public void onCreate() {
    super.onCreate();
    singleton = this;
    MultiDex.install(this);
    Stetho.initializeWithDefaults(this);
    checkAppModeColor(false);
}

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

public void checkAppModeColor(boolean isDarkModeOnly) {
    if (isDarkModeOnly) {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    } else {
        PrefConfig prefConfig = new PrefConfig(this);
        if (prefConfig.getAppTheme().equalsIgnoreCase("Auto")) {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
        } else if (prefConfig.getAppTheme().equalsIgnoreCase("Dark")) {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        } else {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        }
    }
  }
}

The issue is that every time theme changed it restarts the activity and mess up the fragments inside it but theme will be changed. Also there’s 2 sec delay to restart the activity on theme change.

I’ve seen some apps do theme change fluidly without any restart(doesnt look like restart).

I’ve seen in some threads that if I add android:configChanges="uiMode" to AndroidManifest.xml
then Activity will not restart instead onConfigurationChanged will be called and I have to manually change color of every views. Since I have 5 fragments with lists of different viewtypes in the activity, changing color of each item will be hectic. Can anyone suggest any solution for this. Thanks

Source: Android Questions

LEAVE A COMMENT