1. 程式人生 > >android 監聽軟鍵盤在頁面的展開和隱藏

android 監聽軟鍵盤在頁面的展開和隱藏

獲取軟鍵盤狀態思路:

  1. 獲取當前頁面根佈局及其高度 RootH;
  2. 獲取狀態列高度 StatusH和導航欄高度 NavigationH;
  3. 獲取當前根檢視在螢幕上顯示的高度RectH;
  4. 高度差值比較,(根佈局高度 - 根檢視顯示高度)與(狀態列高度 + 導航欄高度)的大小對比;
  5. 大於:展開軟鍵盤
  6. 小於:隱藏軟鍵盤

相關程式碼塊:

viewTree的監聽

// viewTree的監聽
private ViewTreeObserver.OnGlobalLayoutListener keyboardLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            
            // 顯示的根檢視 
            Rect r = new Rect();
            rootLayout.getWindowVisibleDisplayFrame(r);
            
            // 導航欄物件
            Point navigationBarHeight = SystemUtils.getNavigationBarSize(InformationBaseActivity.this);

            // 狀態列高度
            int statusBarHeight = SystemUtils.getStatusBarHeight(InformationBaseActivity.this);
            Log.e(TAG, "navigationBarHeight " + navigationBarHeight.x + " " + navigationBarHeight.y + statusBarHeight);

            // (r.bottom - r.top) 當前頁面根檢視顯示的高度
            // heightDiff 當前頁面原本根佈局高度與顯示檢視的高度差
            int heightDiff = rootLayout.getRootView().getHeight() - (r.bottom - r.top);

            // 高度差判斷是否彈出軟鍵盤
            if (heightDiff > (100 + navigationBarHeight.y + statusBarHeight)) { // if more than 100 pixels, its probably a keyboard...
                mIsShowSoft = true;
                onShowKeyboard(heightDiff);
            } else {
                if (mIsShowSoft) {
                    onHideKeyboard();
                    mIsShowSoft = false;
                }
            }
        }
    };

根佈局對viewTree的實時監聽

 protected void attachKeyboardListeners(int rootViewId) {
        if (keyboardListenersAttached) {
            return;
        }
        rootLayout = findViewById(rootViewId);
        rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(keyboardLayoutListener);

        keyboardListenersAttached = true;
    }

頁面銷燬時移除監聽

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (keyboardListenersAttached) {
            rootLayout.getViewTreeObserver().removeGlobalOnLayoutListener(keyboardLayoutListener);
        }
    }

如何使用:

這些軟鍵盤的監聽操作可部署到基類中,需要用時可呼叫基類中的attachKeyboardListeners(),onShowKeyboard()和onHideKeyboard()方法進行相對應的操作。