Android navigation graph resets onResume
T

0

2

I have a single activity application that uses Android's Navigation Component to navigate between fragments.

I have an issue where, if the app is backgrounded and resumed, the navigation graph returns to the startDestination. Shouldn't the state of the graph (i.e the current fragment) be retained?

Below is a sample of my setup.

MainActivity.kt

class MainActivity: AppCompatActivity() {
private lateinit var binding: MainActivityBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    binding = MainActivityBinding.inflate(layoutInflater)
    setContentView(binding.root)
} }

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:navGraph="@navigation/root_navigation" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

root_navigation.xml

<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/root_navigation.xml"
    app:startDestination="@id/splashFragment">

    <!-- Fragments and actions..... -->
</navigation>

Any help would be greatly appreciated.

Tillfourd answered 11/5, 2022 at 6:18 Comment(4)
What if you change android:id="@+id/root_navigation.xml" to android:id="@+id/root_navigation"?Asp
Unfortunately that didn't work as well @AspTillfourd
Now I wonder how you go away from the splash screen to whatever destination comes firstAsp
@Asp in the end it was a very simple fix. Since MainActivity used be the splash activity before we refactored into a single activity application, it had android:noHistory=true set in the Manifest which was causing this behaviour.Tillfourd

© 2022 - 2024 — McMap. All rights reserved.