Search code examples
androidandroid-studiokotlinandroid-architecture-navigation

Multiple navigation graph app popbackstack does not work


I am currently working on an app that uses android navigation components. The app has multiple navigation graphs that cater for the different navigation in the app.

A user logs into the app, which uses bottom navigation the bottom navbar has a 5 navigation graphs.

From the settings tab, the user can then logout of the application. However, when I press the back button I am taking back to the settings screen.

The settings navigation graph looks as follows :

<?xml version="1.0" encoding="utf-8"?>
<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/settings_graph"
    app:startDestination="@id/settingsFragment">

<fragment
    android:id="@+id/settingsFragment"
    android:name="zw.myexample.ui.SettingsFragment"
    tools:layout="@layout/settings_data">

    <action
        android:id="@+id/action_settingsFragment_to_loginActivity"
        app:destination="@id/toLoginActivity"
        app:popUpTo="@id/login_navigation"
        app:popUpToInclusive="true"/>
</fragment>

<activity
    android:id="@+id/toLoginActivity"
    android:name="zw.myexample.ui.LoginActivity"
    tools:layout="@layout/activity_login" />

</navigation>

In my logout function I have the following:

findNavController().navigate(R.id.action_settingsFragment_to_loginActivity)
findNavController().popBackStack()

This doesn't seem to work, I have tried multiple suggestions in the list below :

Stackoverflow suggested answers


Solution

  • I've figured out that you are moving from one activity (contains setting_fragment) to another activity (contains login fragments). In this scenario, you can start your login_activity after clearing top with the new task.

    I've created this extension function that you can use:

    fun <T : AppCompatActivity> Fragment.gotoActivityWithNoBackUp(targetActivityClass: Class<T>) {
        val intent = Intent(requireActivity(), targetActivityClass)
          .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
          .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
          .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        requireActivity().finish()
        startActivity(intent)
    }
    

    and in your logout button click, copy this code:

    gotoActivityWithNoBackUp(LoginActivity::class.java)