skip to Main Content

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

    }

2

Answers


  1. You can override handleOnBackPressed.

    override fun handleOnBackPressed() {
                binding.yourbutton.setOnClickListener {
                //TODO
            }
    }
    
    Login or Signup to reply.
  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()
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search