Android 監聽軟鍵盤顯示隱藏
阿新 • • 發佈:2019-02-17
開發過程頁面中需要監聽軟鍵盤的顯示和隱藏,無可奈何Android並沒有提供這樣的監聽。
於是乎嘗試各種方法,但是結果總是令人蛋疼。
但是功夫不負有心人,最後還是找到了解決的方法:
當顯示的高度大於整體的2/3時視為鍵盤隱藏(我把鍵盤的高度作為螢幕的1/3高度算的).
/** * 監聽軟鍵盤顯示隱藏 */ private void addSoftInputListener() { View decorView = getWindow().getDecorView(); decorView.getViewTreeObserver().addOnGlobalLayoutListener(newViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Rect rect = new Rect(); decorView.getWindowVisibleDisplayFrame(rect); int displayHight = rect.bottom - rect.top; int hight = decorView.getHeight(); if (displayHight > hight / 3* 2) {
Logger.i("鍵盤隱藏");} else {
Logger.i("鍵盤顯示");} } });}