Android實時監聽軟鍵盤顯示或隱藏
阿新 • • 發佈:2018-12-03
搞了一個實時監聽軟鍵盤顯示或隱藏,當軟鍵盤隱藏了,做邏輯;軟鍵盤顯示出來了,做邏輯;
直接上程式碼了,下面是我寫的工具類,名字為 SoftKeyBoardListener :
import android.app.Activity; import android.graphics.Rect; import android.view.View; import android.view.ViewTreeObserver; /** * Name:Wu. * Date:2018/11/3. * Describe:實時監聽軟鍵盤顯示或隱藏 */ 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 r = new Rect(); rootView.getWindowVisibleDisplayFrame(r); int visibleHeight = r.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; } } }); } private void setOnSoftKeyBoardChangeListener(OnSoftKeyBoardChangeListener onSoftKeyBoardChangeListener) { this.onSoftKeyBoardChangeListener = onSoftKeyBoardChangeListener; } public interface OnSoftKeyBoardChangeListener { void keyBoardShow(int height); void keyBoardHide(int height); } public void setListener(OnSoftKeyBoardChangeListener onSoftKeyBoardChangeListener) { setOnSoftKeyBoardChangeListener(onSoftKeyBoardChangeListener); } }
下面便是用法:
/** * 新增軟鍵盤監聽 */ private void setSoftKeyBoardListener() { softKeyBoardListener = new SoftKeyBoardListener(activity); //軟鍵盤狀態監聽 softKeyBoardListener.setListener(new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() { @Override public void keyBoardShow(int height) { //軟鍵盤已經顯示,做邏輯 } @Override public void keyBoardHide(int height) { //軟鍵盤已經隱藏,做邏輯 } }); }
很簡單,直接呼叫此方法即可;