0

I am listening to the back button pressed on my fragment as follows:

requireActivity().onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                Log.d("backbuttonpressed", "backbuttonpressed ...")
                isEnabled = false
                requireActivity().onBackPressedDispatcher.onBackPressed()
            }
        })

When I pressed the back button at the bottom (screenshot), the hardware back button, the callback gets called but when I press the back button at the top bar it does not get called.

Is there any way to way to know if the top back button has been pressed in Android?

Here is the screenshot of back buttons.

enter image description here

skJosh
  • 631
  • 1
  • 8
  • 16
  • Can you clarify which back button do you need to get notified about? Is it the one on the app bar or the Navbar(Bottom)? Its unclear . – Maleesha97 Jul 19 '23 at 11:31
  • I am new to Android, so sorry that I created confusion here. I will do some correction to the question. Actually, its the back button on the top (app bar). The bottom Navbar works. – skJosh Jul 19 '23 at 11:42

1 Answers1

1
override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return when (item.itemId) {
        android.R.id.home -> {
            // Handle back button press 
            true
        }
        else -> super.onOptionsItemSelected(item)
    }
}

You can Add something like this to your Fragment, It will let you handle the backButton event on the app bar. (android.R.id.home represents your backbutton on the appbar).

Maleesha97
  • 167
  • 1
  • 8
  • Its weird that even onOptionsItemSelected function is not being triggered when I press the back button in the toolbar. – skJosh Jul 19 '23 at 12:12
  • Can you include the xml layout of the button? – Maleesha97 Jul 19 '23 at 12:26
  • 1
    Finally got it working. Seems it works differently with navhostfragment, this one worked for me https://stackoverflow.com/a/61948678/2629576 . Your solution might be useful in some another case I guess but have upvoted. – skJosh Jul 19 '23 at 12:54