Pages

Saturday, April 12, 2014

Hide Sofkeyboard when touched outside EditText in Android

Most of the times we will be entering some values using the EditText while entering values we will be using the softkeyboard and some times we may need to hide the softkeyboard when the user touches outside the the EditText. The following code will implement the functionality where in when the user scrolls or selects outside of the EditText, the softkeyboard will be hidden to the user.

The following code should be in the your activity class for hiding the softkeyboard on the outside click of EditText or while scrolling the UI

@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
            if (getCurrentFocus() != null) {
                  InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                  imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                }
        return super.dispatchTouchEvent(ev);
    }

No comments:

Post a Comment