Android 軟鍵盤的監聽(監聽高度,是否顯示)

Android官方本身沒有提供一共好的方法來對軟鍵盤進行監聽,但我們實際應用時,很多地方都需要針對軟鍵盤來對UI進行一些優化。

public class SoftKeyboardUtil {  
    public static void observeSoftKeyboard(Activity activity, final OnSoftKeyboardChangeListener listener) {  
        final View decorView = activity.getWindow().getDecorView();  
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {  
            int previousKeyboardHeight = -1;  
            @Override  
            public void onGlobalLayout() {  
                Rect rect = new Rect();  
                decorView.getWindowVisibleDisplayFrame(rect);  
                int displayHeight = rect.bottom - rect.top;  
                int height = decorView.getHeight();  
                int keyboardHeight = height - displayHeight;  
                if (previousKeyboardHeight != keyboardHeight) {  
                    boolean hide = (double) displayHeight / height > 0.8;  
                    listener.onSoftKeyBoardChange(keyboardHeight, !hide);  
                }  
  
                previousKeyboardHeight = height;  
  
            }  
        });  
    }  
  
    public interface OnSoftKeyboardChangeListener {  
        void onSoftKeyBoardChange(int softKeybardHeight, boolean visible);  
    }  
}  
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容