Ascorbin Ascorbin - 6 months ago 84
Android Question

Hide soft keyboard on losing focus

When we have an

and it loses focus (to an element that doesn't need a keyboard), should the soft keyboard hide automatically or are we supposed to hide it ourselves?

I'm moving the focus from an
(which should behave like an
I guess) to a
returns true, but the keyboard doesn't hide.


Best way is to set a OnFocusChangeListener for the EditText, and then add the code to the the keyboard into the OnFocusChange method of the listener. Android will then automatically close the keyboard when the EditText loses focus.

Something like this in your OnCreate method:

EditText editText = (EditText) findViewById(;
OnFocusChangeListener ofcListener = new MyFocusChangeListener();

and then add the class:

private class MyFocusChangeListener implements OnFocusChangeListener {

    public void onFocusChange(View v, boolean hasFocus){

        if(v.getId() == && !hasFocus) {

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