I have been messing with the Jetpack Navigation component, and I created an activity that uses a navigation drawer.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val navigationController = findNavController(R.id.navigationHostFragment)
navigationView.setupWithNavController(navigationController)
val appBarConfiguration = AppBarConfiguration(TOP_LEVEL_DESTINATIONS, drawerLayout)
toolbar.setupWithNavController(navigationController, appBarConfiguration)
}
override fun onSupportNavigateUp(): Boolean =
NavigationUI.navigateUp(findNavController(R.id.navigationHostFragment), drawerLayout)
}
This works as I would expect, but then I added a global action for the settings screen.
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
app:startDestination="@id/appBarFragment">
...
<activity android:id="@+id/settingsActivity"
android:name="com.example.app.ui.SettingsActivity"
android:label="@string/title_settings"/>
<action android:id="@+id/settingsAction"
app:destination="@+id/settingsActivity"/>
</navigation>
And reference the action in the NavigationView
menu.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
...
<group android:id="@+id/navigationGroupSettings">
<item android:id="@+id/aboutAction"
android:title="@string/title_about"
android:icon="@drawable/ic_info_black_24dp"/>
<item android:id="@+id/settingsAction"
android:title="@string/title_settings"
android:icon="@drawable/ic_settings_black_24dp"/>
</group>
</menu>
This displays the SettingsActivity
, but when I press the back button to return to the MainActivity
the first destination is displayed, rather than the previous destination. Even though the NavigationView
saves its state correctly, and has the last destination checked (instead of the first item in the list).
I also tried replacing the SettingsActivity
with a SettingsFragment
, with the same result.
How do I get the navigation component to correctly save its state after a global action is selected?