Skip to content

Instantly share code, notes, and snippets.

@zerobranch
Created October 4, 2018 08:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zerobranch/d60681396402869e48dd7d1a59d517e5 to your computer and use it in GitHub Desktop.
Save zerobranch/d60681396402869e48dd7d1a59d517e5 to your computer and use it in GitHub Desktop.
Keyboard visibility utils
import android.app.Activity;
import android.view.View;
import android.view.ViewTreeObserver;
public class KeyboardVisibilityUtils {
private int appHeight;
private final View contentView;
private ViewTreeObserver.OnGlobalLayoutListener layoutListener;
public KeyboardVisibilityUtils(Activity activity) {
contentView = activity.findViewById(android.R.id.content);
}
public void subscribe(OnKeyboardVisibilityListener keyboardVisibilityListener) {
layoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
private int previousHeight;
@Override
public void onGlobalLayout() {
int newHeight = contentView.getHeight();
if (newHeight == previousHeight)
return;
previousHeight = newHeight;
if (newHeight >= appHeight) {
appHeight = newHeight;
}
if (newHeight != 0) {
if (appHeight > newHeight) {
keyboardVisibilityListener.onKeyboardVisibilityChanged(true);
} else {
keyboardVisibilityListener.onKeyboardVisibilityChanged(false);
}
}
}
};
contentView.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);
}
public interface OnKeyboardVisibilityListener {
void onKeyboardVisibilityChanged(boolean keyboardVisible);
}
public void unsubscribe() {
contentView.getViewTreeObserver().removeOnGlobalLayoutListener(layoutListener);
layoutListener = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment