'How can I add click event to onBackPressed in Fragment?
I want to add on-click listener to onBackPressed() button. How can I do that?
fun onBackPressed(it: View) {
val title = binding.edittexttitle.text
val notes = binding.edittextnote.text
val d = Date()
val s: CharSequence = DateFormat.format("MMMM d, yyyy ", d.time)
Log.e("@@@@@", "createNotes: $s")
}
Solution 1:[1]
You can override handleOnBackPressed.
override fun handleOnBackPressed() {
binding.yourbutton.setOnClickListener {
//TODO
}
}
Solution 2:[2]
To override onBackPressed in fragment call onBackPressedDispatcher of the activity and add a callback to it. In callback put whatever code you want to be get executed on the back button press.
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) {
val title = binding.edittexttitle.text
val notes = binding.edittextnote.text
val d = Date()
val s: CharSequence = DateFormat.format("MMMM d, yyyy ", d.time)
Log.e("@@@@@", "createNotes: $s")
}
Afterwards if you want the back button to work as it normally does, just disable callback using isEnabled = false and then call requireActivity().onBackPressed(), inside callback lambda.
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) {
// Your code
isEnabled = false
requireActivity().onBackPressed()
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BurhanYaprak |
| Solution 2 | Praveen |
