Detecting Soft Keyboard Hidden State

纵饮孤独 提交于 2019-12-22 12:53:58

问题


Want to Toast a text everytime when soft keyboard state changes from shown to hidden. Here I just want to getText() from EditText and everytime I click on EditText the soft Keyboard must open and after pressing back or return the text must be shown as Toast

Thanks in Advance


回答1:


There is no direct listener for keyboard state detection so you need some programatic implementation as below

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


来源:https://stackoverflow.com/questions/21379541/detecting-soft-keyboard-hidden-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!