Search code examples
androidandroid-jetpackandroid-jetpack-navigation

BackButton in the Toolbar with Jetpack Navigation is not working (for the first destination)


In the activity XML, I have the fragment tag like,

<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        style="@style/VectorToolbarStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent" />

    <fragment
        android:id="@+id/chat_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_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/toolbar" />
</androidx.constraintlayout.widget.ConstraintLayout>

In the activity code,

    navController = findNavController(R.id.chat_nav_host_fragment)
    navController.setGraph(R.navigation.one_to_one_chat_nav)
    appBarConfiguration = AppBarConfiguration.Builder().build()
    toolbar.setupWithNavController(navController, appBarConfiguration!!)

By doing so, I can see the backbutton with the toolbar. However, the backbutton does not work or the app does not go to the previous activity. If I navigate to the next fragment, backbutton works and brings me to the previous fragment. It only does not work in the first fragment.

Any help or suggestion would be really great. Thanks.


Solution

  • I got a solution. It may not be the best answer. However, its working for now.

        toolbar.setNavigationOnClickListener {
            if(navController.graph.startDestination == navController.currentDestination?.id) {
                finish()
            } else {
                navController.navigateUp()
            }
        }