How to clear focus and remove keyboard on Android?-ThrowExceptions

Exception or error:

I have a EditText control.
If I tap it the softkeyboard will popup however when I press “enter/ok/return” then the EditText control it still has focus and the keyboard up.
How do I close the softkeyboard and remove focus from it?

How to solve:

You could try doing SetFocus() on another element in your layout.

If you are talking about the “enter/ok/return” button on the keyboard itself you may have to set up a KeyListener on the EditText control in order to know when to SetFocus() on another element.


InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editTextField.getWindowToken(), 0);


In the layout XML file, specify an imeOption on your EditText:


Next, add an action listener to your EditText in the Activity’s java file

    mYourEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_GO) {
                // hide virtual keyboard
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mYourEditText.getWindowToken(), 0);
                return true;
            return false;

Where mYourEditText is an EditText object


private void hideDefaultKeyboard() {
   //you have got lot of methods here


Make sure your EditText XML has :


Then set listener to your EditText (with Kotlin, and from a fragment):

myEditText.setOnEditorActionListener({ v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(view!!.windowToken, 0)    

Leave a Reply

Your email address will not be published. Required fields are marked *