Android检测软键盘关闭

Moh*_*oon 6 keyboard android

我正在努力解决这个问题几个小时,我无法找到确定键盘是否显示的方法.

我已经看到了关于这个问题的多个问题和答案,这取决于容器布局的高度变化.因此,当(例如)Edittext获得焦点时,无法准确检测到键盘的打开,因此,全高度布局的变化及其视图是不可避免的.

解决方案1: 我通过从所有EditText中删除焦点来解决这个问题,并在Edittext聚焦时改变我不需要它们的视图的可见性(提供可用空间以防止视图混乱)所以我有足够的删除冗余视图的时间.

但是无法检测何时要求关闭键盘以使视图可见.

如果我使用我在第2段中提到的常用方法来检测键盘的关闭,它将失败我的"解决方案1".

我现在唯一的想法是通过监视键盘关闭来检测键盘关闭.我无法在onKeyDown方法中检测到它.

在此输入图像描述

那么如何监控这个密钥呢?

任何指导和想法将不胜感激.提前致谢.

最终解决方案:
感谢@Nick Cardoso,我的最终解决方案是onTouchListener用于检测键盘开放性和Nick的关闭解决方案的组合.

这是针对Edittexts的onTouchListener:

    View.OnTouchListener TouchListener = new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN)
        {
            Container.getViewTreeObserver().removeOnGlobalLayoutListener(gll);
            recyclerView.setVisibility(View.GONE);
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Container.getViewTreeObserver().addOnGlobalLayoutListener(gll);
                }
            }, 100);
        }
        return false;
    }
};
Run Code Online (Sandbox Code Playgroud)


ViewTreeObserver.OnGlobalLayoutListener gll = new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        Rect measureRect = new Rect();
        Container.getWindowVisibleDisplayFrame(measureRect);
        int keypadHeight = Container.getRootView().getHeight() - measureRect.bottom;

        if (keypadHeight > 0) {
            // keyboard is opened
        } else {
            recyclerView.setVisibility(View.VISIBLE);
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

Container是布局的根视图.

Nic*_*oso 12

(荒谬地)没有简单,可靠的方法来做到这一点.然而,它可以通过两个部分实现,具有这里建议的布局监听器.这有点像黑客但它有效:

mRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        Rect measureRect = new Rect(); //you should cache this, onGlobalLayout can get called often
        mRootView.getWindowVisibleDisplayFrame(measureRect);
        // measureRect.bottom is the position above soft keypad
        int keypadHeight = mRootView.getRootView().getHeight() - measureRect.bottom;

        if (keypadHeight > 0) {
            // keyboard is opened 
            mIsKeyboardVisible = true;
            mMyDependentView.setVisibility(View.GONE);
        } else {
            //store keyboard state to use in onBackPress if you need to
            mIsKeyboardVisible = false;
            mMyDependentView.setVisibility(View.VISIBLE);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)