註冊鍵盤開啟和關閉的回撥

我們的想法是在每次更改之前和之後測量佈局,如果有重大更改,你可以確定它是軟鍵盤。

// 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);