我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
使用AndroidX,我们将获得一种惊人的显示/隐藏键盘的方法。阅读发行说明-1.5.0-alpha02。现在如何隐藏/显示键盘
val controller = view.windowInsetsController
// Show the keyboard
controller.show(Type.ime())
// Hide the keyboard
controller.hide(Type.ime())
链接我自己的答案如何在Android中检查软件键盘的可见性?以及一个包含更多变化(甚至更多)的惊人博客。
其他回答
您还可以研究在EditText上使用setImeOption。
我只是遇到了一个非常模拟的情况,我的布局包含一个EditText和一个搜索按钮。当我发现我可以在editText中将time选项设置为“actionSearch”时,我意识到我甚至不再需要搜索按钮。软键盘(在此模式下)有一个搜索图标,可用于启动搜索(键盘会自动关闭)。
Kotlin中的Wiki答案:
1-在文件中创建顶级函数(例如,包含所有顶级函数的文件):
fun Activity.hideKeyboard(){
val imm = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
var view = currentFocus
if (view == null) { view = View(this) }
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
2-然后在你需要的任何活动中调用它:
this.hideKeyboard()
有时,您可能有一个活动包含包含editText的行的列表视图,因此您必须在清单SOFT_INPUT_ADJUST_PAN中进行设置,然后出现键盘,这很烦人。
如果您将以下工作错误放置在onCreate的末尾,则它会起作用
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
},100);
此代码段可以帮助:
final InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
if (inputMethodManager != null && inputMethodManager.isActive()) {
if (getCurrentFocus() != null) {
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
它可以根据需要以不同的方法调用(例如onPause、onResume、onRestart…)
/**
*
* Hide I Said!!!
*
*/
public static boolean hideSoftKeyboard(@NonNull Activity activity) {
View currentFocus = activity.getCurrentFocus();
if (currentFocus == null) {
currentFocus = activity.getWindow().getDecorView();
if (currentFocus != null) {
return getSoftInput(activity).hideSoftInputFromWindow(currentFocus.getWindowToken(), 0, null);
}
}
return false;
}
public static boolean hideSoftKeyboard(@NonNull Context context) {
if(Activity.class.isAssignableFrom(context.getClass())){
return hideSoftKeyboard((Activity)context);
}
return false;
}
public static InputMethodManager getSoftInput(@NonNull Context context) {
return (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
}