我需要做一件非常简单的事情-找出软件键盘是否显示。这在Android中可行吗?
当前回答
视图#setOnApplyWindowInsetsListener可以用来获得窗口insets回调
public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
getListenerInfo().mOnApplyWindowInsetsListener = listener;
}
//OnApplyWindowInsetsListener
public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
boolean keyboardVisible = insets.isVisible(WindowInsets.Type.ime())可以给出可见性状态。
其他回答
这个解决方案可能会重新打开键盘,但它是有效的。
InputMethodManager inputManager = ( (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE) );
private boolean isKeyboardShowing() {
boolean isKeyboardShowing = inputManager.hideSoftInputFromWindow(irrelevantView.getWindowToken(), 0);
if (isKeyboardShowing) {
inputManager.showSoftInput(this.getCurrentFocus(), 0);
}
return isKeyboardShowing;
}
医生说… https://developer.android.com/reference/androidx/core/view/WindowInsetsCompat
检查放行说明.. https://developer.android.com/jetpack/androidx/releases/core#1.5.0-alpha02
要获得当前键盘可见性,可以使用getRootWindowInsets,然后调用isVisible()函数,传入IME类型。
val windowinsetscompat = ViewCompat.getRootWindowInsets(view)
val imeVisible = windowinsetscompat.isVisible(Type.ime())
也有监听OnApplyWindowInsetsListener的变化
ViewCompat.setOnApplyWindowInsetsListener(view) { v, insets ->
val imeVisible = insets.isVisible(Type.ime())
}
InputMethodManager有关于软键盘的信息。你从一个活动中获得它:
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
你可以摆弄一下,看看它能告诉你什么。你可以用它来显示或隐藏软输入…
我发现@Reuben_Scratton的方法与@Yogesh的方法的组合似乎效果最好。将他们的方法结合起来会产生如下结果:
final View activityRootView = findViewById(R.id.activityRoot);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (getResources().getConfiguration().keyboardHidden == Configuration.KEYBOARDHIDDEN_NO) { // Check if keyboard is not hidden
// ... do something here
}
}
});
这里有一个工作区,以了解软键盘是否可见。
检查系统上正在运行的服务 ActivityManager.getRunningServices (max_count_of_services); 从返回的ActivityManager。运行ningserviceinfo实例,检查软键盘服务的clientCount值。 前面提到的clientCount将在每次显示软键盘时递增。例如,如果clientCount为 一开始是1,显示键盘时是2。 在键盘撤销时,clientCount递减。在本例中,它重置为1。
一些流行的键盘在它们的classname中有特定的关键字:
Google AOSP = IME
Swype = IME
Swiftkey = KeyboardService
Fleksy = keyboard
Adaptxt = IME (KPTAdaptxtIME)
Smart = Keyboard (SmartKeyboard)
从ActivityManager。RunningServiceInfo,在ClassNames中检查上述模式。同时,ActivityManager。RunningServiceInfo的clientPackage=android,表示键盘绑定到系统。
可以将上述信息进行严格的组合,以判断软键盘是否可见。
推荐文章
- 如何允许所有网络连接类型HTTP和HTTPS在Android(9)馅饼?
- Android加载JS包失败
- Android Studio, logcat在应用程序关闭后清理
- 在android中从上下文获取活动
- 无法解析主机"<URL here>"没有与主机名关联的地址
- getActivity()在Fragment函数中返回null
- 按钮背景是透明的
- 在Mac OS X上哪里安装Android SDK ?
- 我如何获得图像缩放功能?
- 在Android应用程序中显示当前时间和日期
- BottomSheetDialogFragment的圆角
- 在应用程序启动时出现“无法获得BatchedBridge,请确保您的bundle被正确打包”的错误
- 我如何改变默认对话框按钮的文本颜色在安卓5
- 更改单选按钮的圆圈颜色
- 如何在android中复制一个文件?