监听虚拟键盘弹出的高度

原理

监听DecorView的可见高度,当虚拟键盘弹出的时候,DecorView的可见高度会变小,这时拿android.R.id.content控件的高度-可见矩形的bottom得到的就是虚拟键盘的高度,代码如下:

public interface KeyboardListener {
    void onKeyboardChange(boolean isPopup, int keyboardHeight);
}
import android.content.Context;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;

public class KeyboardUtils implements ViewTreeObserver.OnGlobalLayoutListener {

    private KeyboardListener listener;
    private int mTempKeyboardHeight;
    private int navigationBarHeight;
    private Activity activity;
    private View decorView;

    public KeyboardUtils(Activity activity,KeyboardListener listener){
        this.activity = activity;
        this.listener = listener;
        decorView = activity.getWindow().getDecorView();
        navigationBarHeight=getNavigationBarHeight(activity);

    }

    public void enable(){
        if(activity!=null) {
            activity.getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(this);
        }
    }

    public void disable(){
        if (activity != null) {
            activity.getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    }


    @Override
    public void onGlobalLayout() {
        if (activity != null) {
            Rect r = new Rect();
            FrameLayout contentView = decorView.findViewById(android.R.id.content);
            decorView.getWindowVisibleDisplayFrame(r);
int screenHeight= contentView.getRootView().getHeight(); int keyboardHeight = screenHeight-r.bottom-navigationBarHeight; if (keyboardHeight != mTempKeyboardHeight) { mTempKeyboardHeight=keyboardHeight; boolean isPopup=false; if (keyboardHeight > navigationBarHeight) { isPopup = true; } if (keyboardHeight < 0) { keyboardHeight = 0; } if (listener != null) { listener.onKeyboardChange(isPopup, keyboardHeight); } } } } private int getNavigationBarHeight(Context context){ int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId>0) { return context.getResources().getDimensionPixelSize(resourceId); } else { return 0; } } }

使用

在Activity中添加以下代码:

  KeyboardUtils keyboardUtils=new KeyboardUtils(this, (isPopup, keyboardHeight) -> {
            Log.d("KeyboardUtils", "onKeyboardChange() called with: isPopup = [" + isPopup + "], keyboardHeight = [" + keyboardHeight + "]");
        });
        keyboardUtils.enable();

 

posted @ 2020-01-19 18:02  南极冰川雪  阅读(355)  评论(0编辑  收藏  举报