Intercept Back Button when closing keyboard and disable blinking cursor

Viewed 154

I have a fragment with EditText used as search bar. What I wanna I do is when I press the back button to close the keyboard, which is opened when clicked on the EditText, is to disable the blinking cursor. For some reason when I'm handling the code below, the cursor still remains visible.

editText.setOnKeyListener{ _, keyCode, event ->
                if(keyCode == KeyEvent.KEYCODE_BACK) {
                    editText.isCursorVisible = false
                    true
                } else {
                    false
                }
        }

I've tried different methods, but none of them gave me the desired result. Am I missing something or is there another method for handling this?

2 Answers

Send the focus to the other component in the page. It should be helpful Or remove focus from your edit text by this code

edittext.clearFocus();

Are you actually trying to clear focus when back button is pressed? From the provided code it looks like you are trying to hide it when back is pressed on keyboard only.

Yes but this implementation is not okay. You should catch the actually backpress event not like you are doing it here. What I think happens here is that the first time you click the back button keyboard hides and you dont receive the back key even. Now if you would press the back button again it would actually hide the cursor. Also the provided code disables the back button, it will only work if the keyboard is opened, otherwise it will just clear the focus and do nothing else

I think something like this would cover your case:

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activity?.onBackPressedDispatcher?.addCallback(this, object : OnBackPressedCallback(false) {
            override fun handleOnBackPressed() {
                editText.clearFocus()
            }
        })
    }
Related