Skip to content

Instantly share code, notes, and snippets.

@Alireza-Farahani
Created December 31, 2020 13:45
Show Gist options
  • Save Alireza-Farahani/d776b0780c9f97252e3ea85d3a909796 to your computer and use it in GitHub Desktop.
Save Alireza-Farahani/d776b0780c9f97252e3ea85d3a909796 to your computer and use it in GitHub Desktop.
Overriding back button in fragments was never this easy!
fun Fragment.overrideBackButtonWith(block: () -> Unit) {
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner,
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
block()
remove() // remove this back button handler
}
})
}
@Alireza-Farahani
Copy link
Author

As an usage example, let's assume we have an Contextual ActionBar and when activiated we want back button to cancel contextual mode

// inside a fragment
// change toolbar/actionbar to contextual
overrideBackButtonWith {
    // end the contextual mode
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment