Created
November 12, 2015 14:47
-
-
Save anonymous/1d5fee1d25c1f1b04dbb to your computer and use it in GitHub Desktop.
detects keyboard show and hide on android software keyboard
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.util.TypedValue; | |
import android.view.View; | |
import android.view.ViewTreeObserver; | |
public class KeyboardDetector implements ViewTreeObserver.OnGlobalLayoutListener, ViewTreeObserver.OnPreDrawListener { | |
private static final int DP_KEYBOARD_THRESHOLD = 60; | |
private int keyboardThreshold; | |
private int currentHeight; | |
private View view; | |
private boolean isKeyboardShown = false; | |
private KeyboardListener listener; | |
public void attachToView(View view, KeyboardListener listener) { | |
this.listener = listener; | |
if (listener == null) return; | |
keyboardThreshold = (int) TypedValue.applyDimension( | |
TypedValue.COMPLEX_UNIT_DIP, DP_KEYBOARD_THRESHOLD, view.getResources().getDisplayMetrics()); | |
this.view = view; | |
currentHeight = view.getHeight(); | |
view.getViewTreeObserver().addOnGlobalLayoutListener(this); | |
if (currentHeight <= 0) { | |
view.getViewTreeObserver().addOnPreDrawListener(this); | |
} | |
} | |
public void detachFromView() { | |
if (view != null) { | |
view.getViewTreeObserver().removeGlobalOnLayoutListener(this); | |
view.getViewTreeObserver().removeOnPreDrawListener(this); | |
view = null; | |
} | |
listener = null; | |
} | |
@Override | |
public void onGlobalLayout() { | |
int newHeight = view.getHeight(); | |
if (currentHeight > 0) { | |
int diff = newHeight - currentHeight; | |
if (diff < -keyboardThreshold) { | |
Log.d(this, "onGlobalLayout. keyboard is show. height diff = " + -diff); | |
// keyboard is show | |
isKeyboardShown = true; | |
if (listener != null) | |
listener.onKeyboardShow(-diff); | |
} else if (diff > keyboardThreshold) { | |
Log.d(this, "onGlobalLayout.keyboard is hide. height diff = " + diff); | |
// keyboard is hide | |
isKeyboardShown = false; | |
if (listener != null) | |
listener.onKeyboardHide(diff); | |
} else { | |
Log.v(this, "onGlobalLayout. height diff = " + diff); | |
} | |
} | |
currentHeight = newHeight; | |
} | |
public boolean isKeyboardShown() { | |
return isKeyboardShown; | |
} | |
@Override | |
public boolean onPreDraw() { | |
currentHeight = view.getHeight(); | |
view.getViewTreeObserver().removeOnPreDrawListener(this); | |
return true; | |
} | |
public interface KeyboardListener { | |
public void onKeyboardShow(int height); | |
public void onKeyboardHide(int height); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment