Skip to content

Instantly share code, notes, and snippets.

@angelkjos
Last active June 13, 2016 10:50
Show Gist options
  • Save angelkjos/a6ba23080caa982d451c3c008f49e5d6 to your computer and use it in GitHub Desktop.
Save angelkjos/a6ba23080caa982d451c3c008f49e5d6 to your computer and use it in GitHub Desktop.
Android Soft-Keyboard listener
// Threshold for minimal keyboard height.
final int MIN_KEYBOARD_HEIGHT_PX = 150;
// Top-level window decor view.
final View decorView = activity.getWindow().getDecorView();
// Register global layout listener.
decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
private final Rect windowVisibleDisplayFrame = new Rect();
private int lastVisibleDecorViewHeight;
@Override
public void onGlobalLayout() {
// Retrieve visible rectangle inside window.
decorView.getWindowVisibleDisplayFrame(windowVisibleDisplayFrame);
final int visibleDecorViewHeight = windowVisibleDisplayFrame.height();
// Decide whether keyboard is visible from changing decor view height.
if (lastVisibleDecorViewHeight != 0) {
if (lastVisibleDecorViewHeight > visibleDecorViewHeight + MIN_KEYBOARD_HEIGHT_PX) {
// Calculate current keyboard height (this includes also navigation bar height when in fullscreen mode).
int currentKeyboardHeight = decorView.getHeight() - windowVisibleDisplayFrame.bottom;
// Notify listener about keyboard being shown.
listener.onKeyboardShown(currentKeyboardHeight);
} else if (lastVisibleDecorViewHeight + MIN_KEYBOARD_HEIGHT_PX < visibleDecorViewHeight) {
// Notify listener about keyboard being hidden.
listener.onKeyboardHidden();
}
}
// Save current decor view height for the next call.
lastVisibleDecorViewHeight = visibleDecorViewHeight;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment