Last active
January 4, 2016 10:11
-
-
Save imran0101/a5cc0434fcad46551109 to your computer and use it in GitHub Desktop.
Observe Keyboard open or hidden
This file contains hidden or 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
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