注册键盘打开和关闭的回调

我们的想法是在每次更改之前和之后测量布局,如果有重大更改,你可以确定它是软键盘。

// A variable to hold the last content layout hight
private int mLastContentHeight = 0;

private ViewTreeObserver.OnGlobalLayoutListener keyboardLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override public void onGlobalLayout() {
        int currentContentHeight = findViewById(Window.ID_ANDROID_CONTENT).getHeight();

        if (mLastContentHeight > currentContentHeight + 100) {
            Timber.d("onGlobalLayout: Keyboard is open");
            mLastContentHeight = currentContentHeight;
        } else if (currentContentHeight > mLastContentHeight + 100) {
            Timber.d("onGlobalLayout: Keyboard is closed");
            mLastContentHeight = currentContentHeight;
        }
    }
};

然后在我们的 onCreate 中设置 mLastContentHeight 的初始值

mLastContentHeight = findViewById(Window.ID_ANDROID_CONTENT).getHeight();

并添加监听器

rootView.getViewTreeObserver().addOnGlobalLayoutListener(keyboardLayoutListener);

不要忘记删除 destroy 上的监听器

rootView.getViewTreeObserver().removeOnGlobalLayoutListener(keyboardLayoutListener);