Skip to content

Instantly share code, notes, and snippets.

@ChristopherME
Created January 28, 2021 11:50
Show Gist options
  • Save ChristopherME/6ca13faeabb567d6d544a7d47e5a8a86 to your computer and use it in GitHub Desktop.
Save ChristopherME/6ca13faeabb567d6d544a7d47e5a8a86 to your computer and use it in GitHub Desktop.
Handle activity backpressed from fragment.
/**
* Extension function for the fragment to handle the activity backPressed().
* Call this inside [Fragment.onAttach] method.
*
* @param backPressed is invoked when the activity triggers onBackPressed().
* @see [https://developer.android.com/reference/androidx/activity/OnBackPressedDispatcher]
*/
inline fun Fragment.handleActivityBackPressed(
crossinline backPressed: () -> Unit
) {
requireActivity().onBackPressedDispatcher.addCallback(
this,
object : OnBackPressedCallback(
true // default to enabled
) {
override fun handleOnBackPressed() {
backPressed()
}
}
)
}
// Usage ->
class MyFragment : Fragment(R.layout.fragment_my) {
...
override fun onAttach(context: Context) {
super.onAttach(context)
handleActivityBackPressed {
//Do something here.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment