In my application i am using Jetpack Navigation with BottomNavigationView
. I have like 4 fragments:Home,Search,Notifications,Profile and when i am in Home fragment, i click again home item in bottom navigation view, it re-creates the fragment. I searched, but mainly answers were for those who did not use jetpack navigation.
(by the way, i only want fragment not being re-created when i am on that fragment already, if i am not in that fragment, it is okay to be re-created)
Below is my setup:
val navHostFragment = supportFragmentManager.findFragmentById(R.id.fragmentContainerView_mainActivity) as NavHostFragment
navController = navHostFragment.navController
binding.bottomNavView.setupWithNavController(navController)
I ended up using code below.(Considering there is not best solution, it works for me as i want)
currentFragmentIndex
is the integer value declared in above scope which shows the fragment we are currently in.
binding.bottomNavView.setOnNavigationItemSelectedListener {
when (it.itemId) {
R.id.homeFragment -> {
if (currentFragmentIndex == 0) {
false
} else {
currentFragmentIndex = 0
navController.navigate(R.id.homeFragment)
true
}
}
R.id.searchFragment -> {
if (currentFragmentIndex == 1) {
false
} else {
currentFragmentIndex = 1
navController.navigate(R.id.searchFragment)
true
}
}
R.id.notificationsFragment -> {
if (currentFragmentIndex == 2) {
false
} else {
currentFragmentIndex = 2
navController.navigate(R.id.notificationsFragment)
true
}
}
R.id.myProfileFragment -> {
if (currentFragmentIndex == 3) {
false
} else {
currentFragmentIndex = 3
navController.navigate(R.id.myProfileFragment)
true
}
}
else -> false
}
}