Skip to content

Instantly share code, notes, and snippets.

@dokinkon
Created August 29, 2016 07:21
Show Gist options
  • Save dokinkon/603fe475931bf6db6e6618b500878d48 to your computer and use it in GitHub Desktop.
Save dokinkon/603fe475931bf6db6e6618b500878d48 to your computer and use it in GitHub Desktop.
public class RxKeyboardVisibilityDetector {
public final static class Change {
public final boolean visible;
public final int height;
Change(boolean visible, int height) {
this.visible = visible;
this.height = height;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Keyboard.Visibility:").append(visible).append("\n");
sb.append("Keyboard.Height:").append(height);
return sb.toString();
}
}
// Threshold for minimal keyboard height.
final private static int MIN_KEYBOARD_HEIGHT_PX = 150;
@NonNull
public static Observable<Change> visibilityChanges(Activity activity) {
return Observable.create(new Observable.OnSubscribe<Change>() {
@Override
public void call(Subscriber<? super Change> subscriber) {
// 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();
Change change = null;
// 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.
change = new Change(true, currentKeyboardHeight);
} else if (lastVisibleDecorViewHeight + MIN_KEYBOARD_HEIGHT_PX < visibleDecorViewHeight) {
// Notify listener about keyboard being hidden.
change = new Change(false, 0);
}
}
// Save current decor view height for the next call.
lastVisibleDecorViewHeight = visibleDecorViewHeight;
if (!subscriber.isUnsubscribed()&&change!=null) {
subscriber.onNext(change);
}
}
});
}
});
}
}
@dokinkon
Copy link
Author

用來判斷鍵盤是否出現,也擷取了高度。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment