Search code examples
javaandroidandroid-fragmentsandroid-fragmentactivityandroid-configchanges

How do I not reset my fragments when configuration changes happen?


So I have this activity that creates 4 fragments for me, which are a bottom navigation bar. when I change to dark mode or light mode, the fragments reset and take me back to the "main fragment" which is basically home in the bottom navigation bar. so my question is how do I stay in the tab I was in while changing UI mode? while of course changing the UI mode of the fragments as well


Solution

  • The best aproach is to let activity recreate itself with its fragments, some configuration changes might be required to show correct UI. And its always possible that your user will move your app to the background, system will kill it after a while and then when your user will go back to it - you will be back with your problem of recreation. I am talking about it to prevent you from using hacks like configChanges in androidmanifest which prevent Activity recreation on configuration change event.

    But back to the main point: when configuration change destroys your Activity, fragments will be automatically recreated when new instance of Activity will be created. But its up to you to save some of its state. I am not sure how your UI and code looks like. The very basic way to save and restore state (like active tab in your question) is to use: Activity.onSaveInstanceState(Bundle) / Activity.onCreate(savedInstanceState: Bundle?) and Fragment.onSaveInstanceState(Bundle)/Fragment.onCreate(savedInstanceState: Bundle?) mechanism. You save relevant variables in bundles in onSaveInstanceState, and later in onCreate restore this state using savedInstanceState variable, but only if its non null - which happens when Activity is created for the first time.

    This is a broad topic, you can find more on this here:

    https://developer.android.com/topic/libraries/architecture/saving-states https://developer.android.com/guide/fragments/saving-state