Created
May 14, 2018 04:15
-
-
Save andhikayuana/58b593a887e5096fd264fa15e316d5ff to your computer and use it in GitHub Desktop.
KeyboardObserve Util for Android
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 { | |
private final static int MAGIC_NUMBER = 200; | |
private SoftKeyboardToggleListener mCallback; | |
private View mRootView; | |
private float mScreenDensity = 1; | |
private static HashMap<SoftKeyboardToggleListener, KeyboardObserver> sListenerMap = new HashMap<>(); | |
public interface SoftKeyboardToggleListener { | |
void onToggleSoftKeyboard(boolean isVisible); | |
} | |
@Override | |
public void onGlobalLayout() { | |
Rect r = new Rect(); | |
mRootView.getWindowVisibleDisplayFrame(r); | |
int heightDiff = mRootView.getRootView().getHeight() - (r.bottom - r.top); | |
float dp = heightDiff / mScreenDensity; | |
if (mCallback != null) | |
mCallback.onToggleSoftKeyboard(dp > MAGIC_NUMBER); | |
} | |
public static void addKeyboardToggleListener(Activity act, SoftKeyboardToggleListener listener) { | |
removeKeyboardToggleListener(listener); | |
sListenerMap.put(listener, new KeyboardObserver(act, listener)); | |
} | |
public static void removeKeyboardToggleListener(SoftKeyboardToggleListener listener) { | |
if (sListenerMap.containsKey(listener)) { | |
KeyboardObserver k = sListenerMap.get(listener); | |
k.removeListener(); | |
sListenerMap.remove(listener); | |
} | |
} | |
public static boolean isRegistered(SoftKeyboardToggleListener listener) { | |
return sListenerMap.containsKey(listener); | |
} | |
public static void removeAllKeyboardToggleListeners() { | |
for (SoftKeyboardToggleListener l : sListenerMap.keySet()) | |
sListenerMap.get(l).removeListener(); | |
sListenerMap.clear(); | |
} | |
private void removeListener() { | |
mCallback = null; | |
mRootView.getViewTreeObserver().removeOnGlobalLayoutListener(this); | |
} | |
private KeyboardObserver(Activity act, SoftKeyboardToggleListener listener) { | |
mCallback = listener; | |
mRootView = ((ViewGroup) act.findViewById(android.R.id.content)).getChildAt(0); | |
mRootView.getViewTreeObserver().addOnGlobalLayoutListener(this); | |
mScreenDensity = act.getResources().getDisplayMetrics().density; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment