Skip to content

Instantly share code, notes, and snippets.

@rajohns08
Last active December 4, 2017 06:34
Show Gist options
  • Save rajohns08/b7b20bb1a49c96a838a7fde6dc76a505 to your computer and use it in GitHub Desktop.
Save rajohns08/b7b20bb1a49c96a838a7fde6dc76a505 to your computer and use it in GitHub Desktop.
Android - Hide keyboard when tapping outside of an EditText
  1. Make your EditText elements be of type FocusChangeEditText in xml.

  2. Set the parent view of your FocusChangeEditText to have xml attributes

     android:clickable="true"
     android:focusableInTouchMode="true"
    

    as described here

public class FocusChangeEditText extends android.support.v7.widget.AppCompatEditText {
public FocusChangeEditText(Context context, AttributeSet attrs) {
super(context, attrs);
OnFocusChangeListener dismissKeyboardOnTapListener = new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
Keyboard.hide(v);
}
}
};
this.setOnFocusChangeListener(dismissKeyboardOnTapListener);
}
}
public class Keyboard {
public static void hide(View view) {
InputMethodManager inputMethodManager = (InputMethodManager)view.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment