Created
October 4, 2018 08:27
-
-
Save zerobranch/d60681396402869e48dd7d1a59d517e5 to your computer and use it in GitHub Desktop.
Keyboard visibility utils
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
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