how to change the fragments using nav controller?

387 Views Asked by At

i am using navigation drawer with navigation components the problem i am facing is navigation is not working i have two fragments dashboard and profile but its not navigation to profile fragment. here is my code can someone help me out for this.

val navHostFragment = supportFragmentManager.findFragmentById(R.id.container) as NavHostFragment
         navController = navHostFragment.navController
        val navView: NavigationView = findViewById(R.id.nav_view)
        appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.dashboardFragment,
               R.id.profileFragment,
            ), drawerLayout
        )
        setupActionBarWithNavController(navController!!, appBarConfiguration!!)
        navView.setupWithNavController(navController!!) 
        navView.setNavigationItemSelectedListener{
            when (it.itemId) {
                R.id.nav_dashboard -> {
                    drawer.closeDrawer(GravityCompat.START)
                }
                R.id.nav_profile -> {
                    drawer.closeDrawer(GravityCompat.START)
                }
            }
            true
        }
1

There are 1 best solutions below

0
On

You are not navigating to the fragment on NavigationItemSelectedListener

Change this From

 navView.setNavigationItemSelectedListener{
            when (it.itemId) {
                R.id.nav_dashboard -> {
                    drawer.closeDrawer(GravityCompat.START)
                }
                R.id.nav_profile -> {
                    drawer.closeDrawer(GravityCompat.START)
                }
            }
            true
        }

To

 navView.setNavigationItemSelectedListener{
            when (it.itemId) {
                R.id.nav_dashboard -> {
                     //R.id.nav_dashboard   should be same as declare in menu.xml   
                    navController.navigate(R.id.navDashboard) //or id of your fragment in navGraph
                }
                R.id.nav_profile -> {
                   navController.navigate(R.id.navProfile) //or id of your fragment in navGraph   
                }
            }
             drawer.closeDrawer(GravityCompat.START)
            true
        }

where navController is initialize in onCreate

 private lateinit var navController: NavController
        navController =
            (supportFragmentManager.findFragmentById(R.id.fragmentNavJob) as NavHostFragment).navController