I am using bottom nav bar. Everything works perfectly but when I open a new fragment and destroy it using back press button my app's going back base fragment but bottom nav bar selected item doesn't change. It stays last clicked position. Let me explain with some pictures
As you can see i'm opening fragment when bottom nav bar's selected item is profile item. Then i'm using back press and going back to main fragment but bottom nav bar's selected item is still profile item.
Host Fragment: The function is inside of onViewcreated (I'm using replacefragment function to set base fragment for first opening)
binding.bottomNavigationView.setOnItemSelectedListener {
when(it.itemId){
R.id.nav_profile -> {replaceFragment(ProfileFragment())
}
R.id.nav_mainpage -> {replaceFragment(MainPageFragment())
}
}
return@setOnItemSelectedListener true
}
replaceFragment(MainPageFragment())
private fun replaceFragment(fragment: Fragment){
val transaction = activity?.supportFragmentManager?.beginTransaction()
transaction?.replace(R.id.frameLayout,fragment)
transaction?.commit()
}
What I tried:I tried this method and it's variants but none of them works
binding.bottomNavigationView.selectedItemId = R.id.nav_mainpage
CodePudding user response:
Try using this:
binding.bottomNavigationView.setSelectedItemId(R.id.nav_mainpage)