Skip to content

Instantly share code, notes, and snippets.

@ksu3101
Created June 28, 2016 01:22
Show Gist options
  • Save ksu3101/dc2000381f93caa736b1aef3a3cb154c to your computer and use it in GitHub Desktop.
Save ksu3101/dc2000381f93caa736b1aef3a3cb154c to your computer and use it in GitHub Desktop.
안드로이드 소프트 키보드에 대한 이벤트 콜백 구현 클래스. 이를 응용해서 Activity에서 활용할 수 있음. 사용 후 destructor()메소드를 꼭 호출 해야 함. (Activity의 onDestroyer등에서 처리)
/**
* activity에서 키보드의 등장유무의 콜백을 구현한 클래스.
*
* @author KangSung-Woo
* @since 2016/06/08
*/
public class SoftKeyboardVisiblityChecker {
/**
* 최소라 생각되는 소프트키보드의 사이즈(pixel)
*/
private static final int MIN_KEYBOARD_HEIGHT = 150;
private View decorView;
private ViewTreeObserver.OnGlobalLayoutListener globalLayoutListener;
public SoftKeyboardVisiblityChecker(Activity activity, OnKeyboardVisibility visibilityListener) {
checkSoftKeyboardOnActivity(activity, visibilityListener);
}
private void checkSoftKeyboardOnActivity(Activity activity, final OnKeyboardVisibility visibilityListener) {
if (activity == null) throw new NullPointerException("activity is null..");
decorView = activity.getWindow().getDecorView();
globalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
private final Rect windowVisibleDisplayFrame = new Rect();
private int lastVisibleDecorViewHeight;
@Override
public void onGlobalLayout() {
// 보여지고 있는 window의 크기를 사각형 Rect객체로 가져 온다.
decorView.getWindowVisibleDisplayFrame(windowVisibleDisplayFrame);
final int visibleDecorViewHeight = windowVisibleDisplayFrame.height();
// 보여지고 있는 높이의 계산 결과에 따라 키보드의 등장 유무를 확인 한다.
if (lastVisibleDecorViewHeight != 0) {
if (lastVisibleDecorViewHeight > visibleDecorViewHeight + MIN_KEYBOARD_HEIGHT) {
final int currentKeyboardHeight = decorView.getHeight() - windowVisibleDisplayFrame.bottom;
// 키보드가 등장중인 상태
if (visibilityListener != null) {
visibilityListener.onKeyboardShown(currentKeyboardHeight);
}
}
else if (lastVisibleDecorViewHeight + MIN_KEYBOARD_HEIGHT < visibleDecorViewHeight) {
// 키보드가 사라진 상태
if (visibilityListener != null) {
visibilityListener.onKeyboardHidden();
}
}
}
lastVisibleDecorViewHeight = visibleDecorViewHeight;
}
};
// global layout listener를 decorview에 등록
decorView.getViewTreeObserver().addOnGlobalLayoutListener(globalLayoutListener);
}
public void desctructor() {
if (decorView != null && globalLayoutListener != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
decorView.getViewTreeObserver().removeOnGlobalLayoutListener(globalLayoutListener);
}
else {
decorView.getViewTreeObserver().removeGlobalOnLayoutListener(globalLayoutListener);
}
}
}
public interface OnKeyboardVisibility {
void onKeyboardShown(int keyboardHeight);
void onKeyboardHidden();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment