smilevchy
1/11/2018 - 6:41 AM

Detect keyboard's open/hide events

...

private View mDecorView;
private OnGlobalLayoutListener mOnGlobalLayoutListener;
private long mLastShowKeyboardTime = -1L;

...


public void onCreate(...) {
  mOnGlobalLayoutListener = new OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                mDecorView.getWindowVisibleDisplayFrame(rect);
                int displayHeight = rect.bottom - rect.top;
                int height = mDecorView.getHeight();
                boolean visible = (double) displayHeight / height < 0.8;

                if (visible) {
                    if (mLastShowKeyboardTime == -1) {
                        mLastShowKeyboardTime = System.currentTimeMillis();
                    }

                    ToastUtil.shortTips("visible");
                } else {
                    if (mLastShowKeyboardTime != -1) {
                        mLastShowKeyboardTime = -1;
                        ToastUtil.shortTips("gone");
                    }
                }
            }
        };

        mDecorView = mContext.getWindow().getDecorView();
        mDecorView.getViewTreeObserver().addOnGlobalLayoutListener(mOnGlobalLayoutListener);
}

@Override
public void onDestroy() {
  if (mDecorView != null && mOnGlobalLayoutListener != null) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
        mDecorView.getViewTreeObserver().removeGlobalOnLayoutListener(mOnGlobalLayoutListener);
    } else {
        mDecorView.getViewTreeObserver().removeOnGlobalLayoutListener(mOnGlobalLayoutListener);
    }
  }

  super.onDestroy();
}