Search code examples
androidkotlinpreference

When i switch the night mode in my PreferenceScreen, my previous screen won't proc onRestart


So i have my SettingsActivity with a PreferenceScreen so I can choose my theme/font settings, along with night mode switch.

I have my function for theme load, that i call in the beginning of onCreate of every activity. Because an activity might be created before we change the settings, I have put an recreate() in onRestart so my function would loadTheme() when the activity gets recreated.

The problem is that while on every changed setting, when I move from MainActivity to SettingsActivity and proc a change to preference settings, onStop() gets called and after I return from SettingActivity back to MainActivity, the onRestart() gets called as it should be.

My problem is if I switch my nightmode option, any other option I change won't take immediate hold on MainActivity because for some reason, even when upon leaving that activity my onStop() gets called, when I return back to it, onRestart() doesn't get called and I don't know why.

Usual lifecycle says that if activity stops, it should call onRestart upon returning back to it. I don't know why switching my night mode would change that. If I move to another activity and then go back to that one, it procs onRestart as usual, it doesn't only immediately after changing the nightmode.

This only happens on API 27 and lower for some reason.

Anyone knows the reason for that?


Solution

  • I solved this by putting this in onPause() of the Main Activity:

    override fun onPause() {
            super.onPause()
            while (rCreate == 0) {
                if (Build.VERSION.SDK_INT < 28) {
                    recreate()
                }
                rCreate = 1
            }
        }
    

    While also declaring a global variable:

    var rCreate: Int = 0
    

    This makes sure that the activity gets recreated after the night mode gets switched which in turn procs the onStop(), which in turn procs onRestart() after returning to view, and this only happens on API 27 or lower.

    If anyone has better solution, feel free.