Hide soft keyboard on losing focus

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(R.id.textbox);
OnFocusChangeListener ofcListener = new MyFocusChangeListener();
editText.setOnFocusChangeListener(ofcListener);

and then add the class:

private class MyFocusChangeListener implements OnFocusChangeListener {

    public void onFocusChange(View v, boolean hasFocus){

        if(v.getId() == R.id.textbox && !hasFocus) {

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

        }
    }
}

Leave a Comment