Skip to content

Instantly share code, notes, and snippets.

@dyguests
Last active October 20, 2018 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dyguests/4a2d80ef63b7ed19247fcdeb234b2f65 to your computer and use it in GitHub Desktop.
Save dyguests/4a2d80ef63b7ed19247fcdeb234b2f65 to your computer and use it in GitHub Desktop.
EditText, clear focus on touch outside

EditText, clear focus on touch outside

Put it in your Activity and it'll apply to all EditTexts including those within fragments within that activity.

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        View v = getCurrentFocus();
        if ( v instanceof EditText) {
            Rect outRect = new Rect();
            v.getGlobalVisibleRect(outRect);
            if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
                v.clearFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
    }
    return super.dispatchTouchEvent( event );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment