欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android 软键盘的监听(监听高度,是否显示)

程序员文章站 2022-04-19 23:09:32
...

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);  
    }  
}