天天看點

android edittext 監聽 鍵盤隐藏,android監聽鍵盤彈出和隐藏

這個确實是個坑啊,android沒有原生的方法支援

從網上看了又修改edittext成功監聽的,Android軟鍵盤彈出和收回監聽

反正在小米上不管事啊,不過點選後退倒是能監聽吧,寫上也沒删除,就當做下相容吧。

最終還是用檢測鍵盤彈出後的螢幕高度來解決的,雖然網友不推薦,但是還是很好用

即使有的螢幕和鍵盤的比例,導緻失敗,咱還有上面的相容,以及檢測EditText聚焦等操作,影響還不是很大。

擷取軟鍵盤狀态思路:擷取目前頁面根布局及其高度 RootH;

擷取狀态欄高度 StatusH和導航欄高度 NavigationH;

擷取目前根視圖在螢幕上顯示的高度RectH;

高度內插補點比較,(根布局高度 - 根視圖顯示高度)與(狀态欄高度 + 導航欄高度)的大小對比;

大于:展開軟鍵盤

小于:隐藏軟鍵盤

相關代碼塊:

viewTree的監聽// viewTree的監聽private ViewTreeObserver.OnGlobalLayoutListener keyboardLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {@Overridepublic 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;}

頁面銷毀時移除監聽@Overridepublic void onDestroy() {super.onDestroy();if (keyboardListenersAttached) {rootLayout.getViewTreeObserver().removeGlobalOnLayoutListener(keyboardLayoutListener);}}

如何使用:

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

參考連結如下