Android 监听软键盘的显示与隐藏

来源:互联网 发布:修改telnet端口 编辑:程序博客网 时间:2024/06/04 20:00

在Android开发中,经常需要监听软键盘的显示状态,而有时候键盘的显示或隐藏是由系统自动调用触发的,但是对系统自动触发的软键盘的显示或隐藏不太方便监听。今天介绍两种监听软键盘显示和隐藏的方法。

第1种方法:
给布局文件最外层的View(在本文中成为mMainView)添加addOnLayoutChangeListener监听,官方文档对该接口的解释是:
Add a listener that will be called when the bounds of the view change due to layout processing.
实例代码如下:

final int mKeyHeight = sScreenHeight / 3; // sScreenHeight为屏幕高度mMainView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {                @Override                public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {                    if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom) > mKeyHeight) {                        Log.d(tag, "软键盘显示");                    } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom) > mKeyHeight) {                        Log.d(tag, "软键盘隐藏")                    }                }            });

第2种方法:
使用ViewTreeObserver的addOnGlobalLayoutListener回调接口实现,官方文档对该接口的解释是:
Register a callback to be invoked when the global layout state or the visibility of views
within the view tree changes.
实例代码如下:

mMainView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {            @Override            public void onGlobalLayout() {                Rect rect = new Rect();                mMainView.getWindowVisibleDisplayFrame(rect);                int displayHeight = rect.bottom - rect.top;                int height = mMainView.getHeight();                boolean visible = (double) displayHeight / height < 0.8;                if (visible) {                    Log.d(tag, "软键盘显示");                } else {                    Log.d(tag, "软键盘隐藏")                }            }        });

下面比较一下这两种方法的优缺点:
第1种方法,适用于windowSoftInputMode=”adjustResize”的情况。在竖屏时使用该方法没有问题,但是在横屏时使用该方法,当软键盘弹出或隐藏时会调用onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom)方法,然而left top right bottom的尺寸与oldLeft oldTop oldRight oldBottom一样,无法判断软键盘显示或隐藏。
第2种方法,在竖屏和横屏使用时,使用该方法都可以判断软键盘的显示与隐藏。但是当View树的状态发生改变或者View树内部的View的可见性发生改变时都会调用onGlobalLayout()方法,这会使该方法多次调用,而这可能会与设置其它View的可见性发生冲突。

1 0
原创粉丝点击