android on back button click action

Viewed 53

I have a single activity and 4 menu. suppose I click on home menu and add a fragment lets say FragmentA and then from FragmentA I add another fragment say FragmentB now when I press back button it returns back to HomeFragment instead of FragmentA. why is so?

2 Answers

You can do it Using popBackStack(); like

  override fun onBackPressed() {
            val manager: FragmentManager = supportFragmentManager
            if(manager.backStackEntryCount > 0){
                manager.popBackStack()
            }else{
                super.onBackPressed()
            }
        }

The back button is used to come back to previous Activity only not Fragment.

Related