Skip to content

Instantly share code, notes, and snippets.

@kibotu
Last active June 14, 2018 08:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kibotu/ee0d5719428571d38ee8 to your computer and use it in GitHub Desktop.
Save kibotu/ee0d5719428571d38ee8 to your computer and use it in GitHub Desktop.
handle hide keyboard functionality on focus lost properly on android
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
final Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (fragment instanceof IDispatchTouchEvent)
return ((IDispatchTouchEvent) fragment).dispatchTouchEvent(ev) || super.dispatchTouchEvent(ev);
return super.dispatchTouchEvent(ev);
}
public static void hideOnLostFocus(@NotNull final Context context, @NotNull final MotionEvent event, @NotNull final View... views) {
boolean hit = false;
for (final View view : views)
hit |= getLocationOnScreen(view).contains((int) event.getX(), (int) event.getY());
if (event.getAction() == MotionEvent.ACTION_DOWN && !hit)
hideKeyboard(context, views[0]);
}
public interface IDispatchTouchEvent {
boolean dispatchTouchEvent(@NotNull final MotionEvent event);
}
public static void hideKeyboard(Context context, View view) {
InputMethodManager imm = (InputMethodManager)context.getSystemService("input_method");
if(imm != null) {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment