Android如何监听输入框的出现和隐藏

类实现:

  public SoftKeyboardState(Activity activity) {
    this.decorView = activity.findViewById(android.R.id.content);
    initKeyboardListener();
  }

  private void initKeyboardListener() {
    decorView.getViewTreeObserver().addOnGlobalLayoutListener(
      new ViewTreeObserver.OnGlobalLayoutListener(){
        private final Rect windowVisibleDisplayFrame = new Rect();
        private int lastVisibleDecorViewHeight;

        @Override
        public void onGlobalLayout() {
          decorView.getWindowVisibleDisplayFrame(windowVisibleDisplayFrame);
          final int visibleDecorViewHeight = windowVisibleDisplayFrame.height();

          Log.i(TAG,"  onGlobalLayout called " + visibleDecorViewHeight+ "  "+ lastVisibleDecorViewHeight);

          if (lastVisibleDecorViewHeight != 0) {
            if (lastVisibleDecorViewHeight - visibleDecorViewHeight > 200) {
              if (listener != null)listener.onKeyboardStateChanged(true);
            } else if (visibleDecorViewHeight - lastVisibleDecorViewHeight > 200) {
              if (listener != null)listener.onKeyboardStateChanged(false);
            }
          }
          lastVisibleDecorViewHeight = visibleDecorViewHeight;
        }
      });
  }

  public void setOnKeyboardStateChangedListener(OnKeyboardStateChangedListener listener) {
    this.listener = listener;
  }

  public interface OnKeyboardStateChangedListener {
     void onKeyboardStateChanged(boolean isShown);
  }
}

注意以上类只能监听普通的activity,如果theme中有如下设置,会不生效:

        true

你可能感兴趣的:(技术android)