/** * Time:2019/6/6 * Author:Ayinger * Description: 實時監聽軟鍵盤顯示或者隱藏 */ public class SoftKeyBoardListener { private View rootView; // activity的根視圖 int rootViewVisibleHeight; // 記錄根視圖顯示的高度 private OnSoftKeyBoardChangeListener onSoftKeyBoardChangeListener; public SoftKeyBoardListener(Activity activity){ // 獲取activity的根視圖 rootView = activity.getWindow().getDecorView(); // 監聽視圖樹中全局布局發生改變或者視圖樹中某個視圖的可視狀態發生改變 rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // 獲取當前根視圖在屏幕上顯示的大小 Rect rect = new Rect(); rootView.getWindowVisibleDisplayFrame(rect); int visibleHeight = rect.height(); if(rootViewVisibleHeight == 0){ rootViewVisibleHeight = visibleHeight; return; } //根視圖顯示高度沒有變化,可以看做軟鍵盤顯示/隱藏狀態沒有變化 if(rootViewVisibleHeight == visibleHeight){ return; } // 根視圖顯示高度變小超過200,可以看做軟鍵盤顯示了 if(rootViewVisibleHeight -visibleHeight > 200){ if(onSoftKeyBoardChangeListener !=null){ onSoftKeyBoardChangeListener.keyBoardShow(rootViewVisibleHeight - visibleHeight); } rootViewVisibleHeight = visibleHeight; return; } // 根視圖顯示高度變大超過了200,可以看做軟鍵盤隱藏了 if(visibleHeight - rootViewVisibleHeight > 200){ if(onSoftKeyBoardChangeListener != null){ onSoftKeyBoardChangeListener.keyBoardHide(visibleHeight - rootViewVisibleHeight); } rootViewVisibleHeight = visibleHeight; return; } } }); } public interface OnSoftKeyBoardChangeListener{ void keyBoardShow(int height); void keyBoardHide(int height); } public void setOnSoftKeyBoardChangeListener(OnSoftKeyBoardChangeListener onSoftKeyBoardChangeListener) { this.onSoftKeyBoardChangeListener = onSoftKeyBoardChangeListener; } }
調用方式:
/** * 添加軟鍵盤的監聽 */ private void setSoftKeyBoardListener(){ softKeyBoardListener = new SoftKeyBoardListener(this); softKeyBoardListener.setOnSoftKeyBoardChangeListener(new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() { @Override public void keyBoardShow(int height) { Toast.makeText(MainActivity.this, "顯示:"+height, Toast.LENGTH_SHORT).show(); } @Override public void keyBoardHide(int height) { Toast.makeText(MainActivity.this, "隱藏:"+height, Toast.LENGTH_SHORT).show(); } }); }
參考博客:https://blog.csdn.net/wuqingsen1/article/details/84760820