Skip to content

Instantly share code, notes, and snippets.

@AndrewReitz
Last active May 19, 2017 15:03
Show Gist options
  • Save AndrewReitz/18e5741eeb32b6236a487b7128f416c1 to your computer and use it in GitHub Desktop.
Save AndrewReitz/18e5741eeb32b6236a487b7128f416c1 to your computer and use it in GitHub Desktop.
KeyboardHider (Android)
/**
* Provides a simple way to hide a keyboard, because google didn't
*/
@Singleton
public final class KeyboardHider {
private final InputMethodManager inputMethodManager;
@Inject KeyboardHider(InputMethodManager inputMethodManager) {
this.inputMethodManager = checkNotNull(inputMethodManager, "inputMethodManager == null");
}
/**
* Hides a keyboard if one is being displayed.
*
* @param activity The current activity.
* @throws NullPointerException if activity is null
*/
public void hideKeyboard(Activity activity) {
// Find the currently focused view, so we can grab the correct window token from it.
View view = checkNotNull(activity, "activity == null").getCurrentFocus();
// If no view currently has focus, create a new one, just so we can grab a window token from it
if (view == null) {
view = new View(activity);
}
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment