How to save navigation state between configuration changes?

593 views Asked by At

I have an android compose app that is set up with a single activity that uses NavController to navigate between screens.

However, when I rotate the screen (make a configuration change) the screen resets to the startDestination specified in the NavHost.

How can I preserve the nav state between configuration changes?

1

There are 1 answers

0
Advitiay Anand On

It's quite simple, really.

The reason you keep going back to your startDestination is because configuration changes destroy and recreate the current activity.

You need to disable activity recreation by specifying it in your AndroidManifest.xml

For example, adding the following attribute under an activity's tag would let you rotate the screen without destroying that activity, thereby preserving your navigation state:

android:configChanges="orientation|screenSize|screenLayout"

Android Documentation Sources

  1. Handle Configuration Changes
  2. Possible Values for the android:configChanges attribute