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

Published

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.
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) {
                Navigation.findNavController(this, R.id.navHost).navigate(R.id.goto_secondFragment)
            }
            if (id == R.id.secondFragment) {
                Navigation.findNavController(this, R.id.navHost).navigate(R.id.goto_thirdFragment)

            }
        }
    }

}

Source: Android Questions

Published
Categorized as android, fragment, kotlin

Answers

Leave a Reply

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq