Last active
June 13, 2016 10:50
-
-
Save angelkjos/a6ba23080caa982d451c3c008f49e5d6 to your computer and use it in GitHub Desktop.
Android Soft-Keyboard listener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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