Search code examples
androidkotlinfragment

Not getting current fragment id using navController.currentDestination?.id


I have a activity with a button and below that I have navhost fragment with 3 fragments. But when I click on button nothing happens, I thick because id of fragment is not getting. enter image description here Here is my code :

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)

        val navHostFragment = supportFragmentManager.findFragmentById(R.id.navHost) as NavHostFragment
        val navController = navHostFragment.navController
        val id = navController.currentDestination?.id

        binding.myButton.setOnClickListener {
            if (id == R.id.firstFragment) {
                navController.navigate(R.id.goto_secondFragment)
            }
            if (id == R.id.secondFragment) {
                navController.navigate(R.id.goto_thirdFragment)

            }
        }
    }

}

Solution

  • The problem is you are getting currentDestination id only once because onCreate is called when the activity is created and you want to check that on which fragment currently you are when you click on Button so just move

    this

    val id = navController.currentDestination?.id
    

    into on click of button

    like this

            binding.myButton.setOnClickListener {
               val id = navController.currentDestination?.id
                if (id == R.id.firstFragment) {
                    navController.navigate(R.id.goto_secondFragment)
                }
                if (id == R.id.secondFragment) {
                    navController.navigate(R.id.goto_thirdFragment)
    
                }
            }
    

    now what will happen is when you click on next or previous button it will first get the current destination id then it will check that in which fragment you are now.