Home > Mobile >  How can i add click event to onBackpressed in Android Studio Fragment?
How can i add click event to onBackpressed in Android Studio Fragment?

Time:05-04

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")

    }

CodePudding user response:

You can override handleOnBackPressed.

override fun handleOnBackPressed() {
            binding.yourbutton.setOnClickListener {
            //TODO
        }
}

CodePudding user response:

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()
}
  • Related