-
Notifications
You must be signed in to change notification settings - Fork 77
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Simple example to handle back button INSIDE fragment #258
Comments
Used this approach
Inside fragment
Not sure if this can be improved 🤔 @Zhuinden |
This is my current code for this private val backPressedCallback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
val topKey = backstack.top<FragmentKey>()
val fragment = supportFragmentManager.findFragmentByTag(topKey.fragmentTag)
if (fragment is BackHandler) {
val handled = fragment.onBackPressed()
if (handled) {
return
}
}
val handled = Navigator.onBackPressed(this@MainActivity)
if (handled) {
return
}
// default fallback
this.remove() // this is the only safe way to invoke onBackPressed while cancelling the execution of this callback
onBackPressed() // this is the only safe way to invoke onBackPressed while cancelling the execution of this callback
this@MainActivity.onBackPressedDispatcher.addCallback(this) // this is the only safe way to invoke onBackPressed while cancelling the execution of this callback
}
}
// ...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
onBackPressedDispatcher.addCallback(backPressedCallback)
...
}
@Suppress("RedundantModalityModifier")
override final fun onBackPressed() {
super.onBackPressed() // onBackPressed() was killed by Google (thanks Google)
} And interface BackHandler {
fun onBackPressed(): Boolean
} Then in my Fragment I can do this: override fun onBackPressed(): Boolean {
if(...) {
...
return true
}
return false
} But when using this hacky-looking approach using // Fragment onViewCreated
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, backPressedCallback)
backPressedCallback.isEnabled = isOverlayShowing
} |
(readme section not very clear) |
@omkar-tenkale if you want to use It is a major design oversight from Google, actually. It took me a while to be convinced that yes, removing the callback and re-adding the callback is the correct way to do it. In fact, it is the only correct way to do it. 🤨 But it also comes with that targetSdkVersion 34 and Android Tiramisu deprecates |
oh, got it now, thx! |
i know its possible with ScopedServices.HandlesBack but donno how
The text was updated successfully, but these errors were encountered: