我们有一个在条形码扫描仪 Android 设备 (ScanSKU) 上运行的应用程序。每当用户扫描任何内容时,键盘都会在“键入”他们扫描的文本时显示,并会挡住一半的屏幕。
我们的应用程序基本上是一个WebView,我们仍然需要能够将表单元素集中在其中。
但是我们是否可以构建一个切换按钮来禁用屏幕键盘在 WebView 中时出现?
我尝试过使用这个:
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
来自:Close/hide the Android Soft Keyboard
但没有成功。
关于如何解决这个问题有什么建议或想法吗?
最佳答案
还有另一种方法可以获取焦点 View ,getCurrentFocus 方法也不适合我。尝试这个解决方案,您应该提供 Activity 对象的实例。
public static void hideSoftKeyboard(Context context) {
try {
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(((Activity) context).getWindow().getDecorView().getRootView().getWindowToken(), 0);
((Activity) context).getWindow().getDecorView().getRootView().clearFocus();
} catch (NullPointerException e) {
// some error log
}
}
已编辑:如果您使用 WebView 并且仍然需要能够将表单元素聚焦在其中。您可以设置属性
view.setFocusableInTouchMode(false);
对于屏幕上的其他 View ,WebView 将保持焦点。
关于java - 以编程方式切换软键盘的隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47159663/