2

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

Image 1 +++ Image 2 +++ Image 3

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
Tunahan
  • 194
  • 1
  • 11

1 Answers1

1

Try using this:

        binding.bottomNavigationView.setSelectedItemId(R.id.nav_mainpage)
Danish
  • 676
  • 5
  • 10
  • I've already tried it doesn't work unfotunately. This method just work when app is opening for the first time. – Tunahan Oct 17 '21 at 14:39
  • 1
    Refer to this answer https://stackoverflow.com/a/6505060/14979180 – Danish Oct 18 '21 at 06:58
  • 1
    Then on your fragment onResume() method set the bottom.nav bar item to MainPage. – Danish Oct 18 '21 at 07:11
  • OnCreate() method is called when activity is first created i.e. onCreate() method will not be called unless you close your app and re launch it while onResume() is called whenever you move from one activity/fragment to other(onPause() is called here) then again come back to that same activity/fragment(onResume() is called).So in your case onCreate() isnt called when you came back to your main fragment from ur 2nd fragment,onResume() was called at this point so your code worked here. – Danish Oct 20 '21 at 05:08
  • Are you familiar with android activity lifecycle? – Danish Oct 20 '21 at 05:10