Skip to content

Instantly share code, notes, and snippets.

@mistrydarshan99
Forked from vaibhav-jani/KeyboardUtils.java
Last active August 28, 2015 10:50
Show Gist options
  • Save mistrydarshan99/95e5cab4395614175f01 to your computer and use it in GitHub Desktop.
Save mistrydarshan99/95e5cab4395614175f01 to your computer and use it in GitHub Desktop.
KeyboardUtils
public class KeyboardUtils {
public static void setKeyboardVisibilityListener(Activity activity, final KeyboardVisibilityListener keyboardVisibilityListener) {
final View contentView = activity.findViewById(android.R.id.content);
contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
private int mPreviousHeight;
@Override
public void onGlobalLayout() {
int newHeight = contentView.getHeight();
if (mPreviousHeight != 0) {
if (mPreviousHeight > newHeight) {
// Height decreased: keyboard was shown
keyboardVisibilityListener.onKeyboardVisibilityChanged(true);
} else if (mPreviousHeight < newHeight) {
// Height increased: keyboard was hidden
keyboardVisibilityListener.onKeyboardVisibilityChanged(false);
} else {
// No change
}
}
mPreviousHeight = newHeight;
}
});
}
public interface KeyboardVisibilityListener {
void onKeyboardVisibilityChanged(boolean keyboardVisible);
}
public static void hideKeyboard(Activity activity) {
try {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
Logger.e(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment