Android 软键盘的监听事件

时间:2022-04-27 12:36:30
/**
 * 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