Created
January 28, 2021 11:50
-
-
Save ChristopherME/6ca13faeabb567d6d544a7d47e5a8a86 to your computer and use it in GitHub Desktop.
Handle activity backpressed from fragment.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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