Skip to content

Instantly share code, notes, and snippets.

@imran0101
Last active January 4, 2016 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save imran0101/a5cc0434fcad46551109 to your computer and use it in GitHub Desktop.
Save imran0101/a5cc0434fcad46551109 to your computer and use it in GitHub Desktop.
Observe Keyboard open or hidden
public class KeyboardObserver implements ViewTreeObserver.OnGlobalLayoutListener {
public interface Callback {
void onKeyboardVisible();
void onKeyboardHidden();
}
WeakReference<View> view;
Callback callback;
public KeyboardObserver(View view, Callback callback) {
this.view = new WeakReference<>(view);
this.callback = callback;
}
/**
* subscribe to start observing keyboard changes
*/
public void subscribe() {
this.view.get().getViewTreeObserver().addOnGlobalLayoutListener(this);
}
/**
* Unsubscribe to remove listener and avoid leaks
*/
public void unsubscribe() {
this.view.get().getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
@Override
public void onGlobalLayout() {
Rect r = new Rect();
view.get().getWindowVisibleDisplayFrame(r);
int screenHeight = view.get().getRootView().getHeight();
// r.bottom is the position above soft keypad or device button.
// if keypad is shown, the r.bottom is smaller than that before.
int keypadHeight = screenHeight - r.bottom;
if (keypadHeight > screenHeight * 0.20) { // 0.20 ratio is perhaps enough to determine keypad height.
// keyboard is opened
if (callback != null) {
callback.onKeyboardVisible();
}
} else {
// keyboard is closed
if (callback != null) {
callback.onKeyboardHidden();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment