我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
有时你只需要按回车键来折叠键盘在“编辑文本”框中指定属性
android:imeOptions="actionDone"
这将将Enter按钮更改为Done按钮,该按钮将关闭键盘。
其他回答
与Android 10(API 29)一起工作
val activityView = activity?.window?.decorView?.rootView
activityView?.let {
val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.hideSoftInputFromWindow(it.windowToken, 0)
}
有时你只需要按回车键来折叠键盘在“编辑文本”框中指定属性
android:imeOptions="actionDone"
这将将Enter按钮更改为Done按钮,该按钮将关闭键盘。
private void hideSoftKeyboard() {
View view = getView();
if (view != null) {
InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
我正在使用自定义键盘输入十六进制数,因此无法显示IMM键盘。。。
在v3.2.4_r1中,添加了setSoftInputShownOnFocus(布尔显示)来控制天气或在TextView获得焦点时不显示键盘,但它仍然隐藏,因此必须使用反射:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
try {
Method method = TextView.class.getMethod("setSoftInputShownOnFocus", boolean.class);
method.invoke(mEditText, false);
} catch (Exception e) {
// Fallback to the second method
}
}
对于较旧的版本,我使用OnGlobalLayoutListener获得了非常好的结果(但远非完美),在根视图的ViewTreeObserver的帮助下添加,然后检查键盘是否显示如下:
@Override
public void onGlobalLayout() {
Configuration config = getResources().getConfiguration();
// Dont allow the default keyboard to show up
if (config.keyboardHidden != Configuration.KEYBOARDHIDDEN_YES) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mRootView.getWindowToken(), 0);
}
}
最后一个解决方案可能会在一秒钟内显示键盘,并干扰选择手柄。
当键盘进入全屏时,不会调用onGlobalLayout。要避免这种情况,请在TextView XML声明中使用TextView#setImeOptions(int)或:
android:imeOptions="actionNone|actionUnspecified|flagNoFullscreen|flagNoExtractUi"
更新:刚刚发现对话框用于从不显示键盘,并且在所有版本中都有效:
getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
在我的案例中,我使用的是操作栏中的SearchView。用户执行搜索后,键盘将再次弹出。
使用InputMethodManager未关闭键盘。我必须清除Focus并将搜索视图的可聚焦设置为false:
mSearchView.clearFocus();
mSearchView.setFocusable(false);