I\'m writing an application which will have two Activities, when the user presses the back button on the second activity a dialog should pop up asking the user to confirm th
By the docs, do not use onBackPressed
if you can. Now is recommended using onBackPressedDispatcher.addCallback(this) {}
. There's a Fragment example:
class MyFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// This callback will only be called when MyFragment is at least Started.
val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
// Handle the back button event
}
// The callback can be enabled or disabled here or in the lambda
}
...
}