我在这个问题上苦苦挣扎了几个小时,但我找不到确定键盘是否显示的方法。
我已经看到关于这个问题的多个问题和答案,这取决于容器布局高度的变化。因此,当(例如)一个 Edittext 获得焦点时,不可能准确地检测到键盘的打开,因此,全高布局及其 View 的变化是不可避免的。
解决方案 1: 我通过从所有 EditText 中移除焦点并更改 View 的可见性解决了这个问题,当 Edittext 获得焦点时我不需要它们显示(腾出可用空间以防止 View 困惑)所以我有足够的时间删除多余的 View 。
但无法检测何时要求关闭键盘以使 View 可见。
如果我使用我在第 2 段中提到的常用方法来检测键盘的关闭,它将使我的“解决方案 1”失败。
我现在唯一的想法是通过监视负责键盘关闭的键来检测键盘关闭。机器人我无法在 onKeyDown 方法中检测到它。
那么我该如何监控这个 key 呢?
任何指南和想法将不胜感激。 提前致谢。
最终解决方案:
感谢@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;
}
};
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);
}
}
};
这里的 Container
是布局的 Root View 。
最佳答案
没有(可笑的)简单、可靠的方法来做到这一点。然而,它可以分两部分实现,按照建议使用布局监听器 here .这有点 hack,但它有效:
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);
}
}
});
关于Android检测软键盘关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42892419/