2

I have an app with single activity and bottom navigation view..

There are 4 items in bottom navigation so i have 4 fragments for it..

My question is how can I handle back stack with bottom navigation view like Youtube or Instagram?

I'm using Kotlin and this is my code:

  nav_view.setOnNavigationItemSelectedListener {
        when (it.itemId) {
            R.id.navigation_home -> {
                replaceFragment(homeFragment)
                true
            }
            R.id.navigation_projects -> {
                replaceFragment(projectsFragment)
                true
            }
            R.id.navigation_team -> {
                replaceFragment(teamFragment)
                true
            }
            R.id.navigation_contact -> {
                replaceFragment(contactUsFragment)
                true
            }
            else -> false
        }
    }

private fun replaceFragment(fragment: Fragment) {
    supportFragmentManager.beginTransaction()
        .replace(R.id.fragment_container, fragment)
        .commit()
}

override fun onBackPressed() {
    if (nav_view.selectedItemId == R.id.navigation_home) {
        super.onBackPressed()
    } else {
        nav_view.selectedItemId = R.id.navigation_home
    }
}
Hemant N. Karmur
  • 840
  • 1
  • 7
  • 21
Hasan Al-Qaisi
  • 167
  • 3
  • 11
  • use addToBackStack with begin transaction and pop it on back press – Hooman Jan 19 '20 at 14:16
  • Does this answer your question? [Android Jetpack Navigation, BottomNavigationView with Youtube or Instagram like proper back navigation (fragment back stack)?](https://stackoverflow.com/questions/50577356/android-jetpack-navigation-bottomnavigationview-with-youtube-or-instagram-like) – Bincy Baby May 08 '23 at 06:49

1 Answers1

0

I think you also need to replace the fragment too like this:

override fun onBackPressed() {
    if (nav_view.selectedItemId == R.id.navigation_home) {
        super.onBackPressed()
    } else {
        nav_view.selectedItemId = R.id.navigation_home
        replaceFragment(homeFragment) // add this line
    }
}
Atiq
  • 14,435
  • 6
  • 54
  • 69
  • Thanks but i don't want it to navigate back to home fragment.. I want it to implement the back stack like Youtube does – Hasan Al-Qaisi Jan 19 '20 at 22:52
  • and what YouTube app does? – Atiq Jan 19 '20 at 23:05
  • If you navigate between fragments with bottom navigation view then click the back button it will navigate to the previous fragments each time you click the back button – Hasan Al-Qaisi Jan 19 '20 at 23:12
  • oh you mean you want to keep track of history, for that I would recommend [FragNav](https://github.com/ncapdevi/FragNav) – Atiq Jan 19 '20 at 23:36