我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
下面是如何在Mono for Android(AKA MonoDroid)中实现的
InputMethodManager imm = GetSystemService (Context.InputMethodService) as InputMethodManager;
if (imm != null)
imm.HideSoftInputFromWindow (searchbox.WindowToken , 0);
其他回答
您可以使用InputMethodManager强制Android隐藏虚拟键盘,调用hideSoftInputFromWindow,传入包含焦点视图的窗口的标记。
// 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);
}
这将在所有情况下强制隐藏键盘。在某些情况下,您需要将InputMethodManager.HIDE_IMPLICIT_ONLY作为第二个参数传递,以确保仅在用户未显式强制显示键盘时(通过按住菜单)隐藏键盘。
注意:如果您想在Kotlin中执行此操作,请使用:上下文getSystemService(Context.INPUT_METHOD_SERVICE)作为InputMethodManager
Kotlin语法
// Only runs if there is a view that is currently focused
this.currentFocus?.let { view ->
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.hideSoftInputFromWindow(view.windowToken, 0)
}
使用这个
this.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
此代码段可以帮助:
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…)
在Kotlin试试这个
private fun hideKeyboard(){
val imm = activity!!.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(activity!!.currentFocus!!.windowToken, 0)
}
在Java中尝试
private void hideKeyboard(){
InputMethodManager imm =(InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
public void setKeyboardVisibility(boolean show) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if(show){
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}else{
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0);
}
}