Forked from billylindeman/KeyboardStatusDetector.java
Created
February 4, 2021 12:06
-
-
Save Anr-C/d8fd0ccb5150bdabe598a964f5c794eb to your computer and use it in GitHub Desktop.
This is a KeyboardStatusDetector for android that uses a globalLayoutListener to dispatch events if a Softkeyboard is shown or hidden
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.app.Fragment; | |
import android.graphics.Rect; | |
import android.view.View; | |
import android.view.ViewTreeObserver.OnGlobalLayoutListener; | |
/** | |
* Detects Keyboard Status changes and fires events only once for each change | |
*/ | |
public class KeyboardStatusDetector { | |
KeyboardVisibilityListener visibilityListener; | |
boolean keyboardVisible = false; | |
public void registerFragment(Fragment f) { | |
registerView(f.getView()); | |
} | |
public void registerActivity(Activity a) { | |
registerView(a.getWindow().getDecorView().findViewById(android.R.id.content)); | |
} | |
public KeyboardStatusDetector registerView(final View v) { | |
v.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { | |
@Override | |
public void onGlobalLayout() { | |
Rect r = new Rect(); | |
v.getWindowVisibleDisplayFrame(r); | |
int heightDiff = v.getRootView().getHeight() - (r.bottom - r.top); | |
if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard... | |
/** Check this variable to debounce layout events */ | |
if(!keyboardVisible) { | |
keyboardVisible = true; | |
if(visibilityListener != null) visibilityListener.onVisibilityChanged(true); | |
} | |
} else { | |
if(keyboardVisible) { | |
keyboardVisible = false; | |
if(visibilityListener != null) visibilityListener.onVisibilityChanged(false); | |
} | |
} | |
} | |
}); | |
return this; | |
} | |
public KeyboardStatusDetector setVisibilityListener(KeyboardVisibilityListener listener) { | |
visibilityListener = listener; | |
return this; | |
} | |
public static interface KeyboardVisibilityListener { | |
public void onVisibilityChanged(boolean keyboardVisible); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment