How do I switch between fragments?

65 Views Asked by At

I have 3 fragments and I am controlling them with a nav_graph. The first one is listingEvents, the second one is listingItemsOfEvents and the last one is updateListing items. When I update items and click "Update" button, It goes tolistingItemsOfEvents fragment, it is nice. However on listinlistingItemsOfEvents when I click the back button(I drew blue color on second picture) I want to open listingEvents fragment. With my codes it returns update fragments. How I can open listingEvents fragment when I click the back button(I drew blue color on second picture)?

Update Fragment

enter image description here

navGraph

1

There are 1 best solutions below

1
On

To handle navigation when the user chooses Up from the action bar, override onSupportNavigateUp with returning navController.navigateUp() in your host activity like this,

class MainActivity : AppCompatActivity(R.layout.activity_main) {

    private lateinit var navController: NavController

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

        // Retrieve NavController from the NavHostFragment
        val navHostFragment = supportFragmentManager
                .findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        navController = navHostFragment.navController

        // Set up the action bar for use with the NavController
        setupActionBarWithNavController(navController)
    }

    /**
     * Handle navigation when the user chooses Up from the action bar.
     */
    override fun onSupportNavigateUp(): Boolean {
        return navController.navigateUp() || super.onSupportNavigateUp()
    }
}