检测软键盘隐藏状态

时间:2014-01-27 11:22:05

标签: android android-softkeyboard

每当软键盘状态从显示更改为隐藏时,都希望Toast一个文本。在这里,我只想getText()来自EditText,每次点击EditText软键盘都必须打开,按回或返回后,文字必须显示为Toast

提前致谢

1 个答案:

答案 0 :(得分:6)

键盘状态检测没有直接监听器,因此您需要一些程序化实现,如下所示

private boolean wasKeyboardOpen = false;

try {
        activityMainView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                Rect r = new Rect();
                activityMainView.getWindowVisibleDisplayFrame(r);

                int heightDiff = activityMainView.getRootView().getHeight() - (r.bottom - r.top);
                if (heightDiff > 100) {
                    wasKeyboardOpen = true;
                    // kEYBOARD IS OPEN

                } else {
                    if (wasKeyboardOpen) {
                        wasKeyboardOpen = false;
                        // Do your toast here

                    }
                    // kEYBOARD IS HIDDEN
                }
            }
        });
    } catch (Throwable e) {
        e.printStackTrace();
    }