如何设置安卓软键盘的可见性

我的布局中有一个EditText'和一个Button'。

在编辑栏里写完字并点击 "按钮 "后,我想隐藏虚拟键盘。我想这是一段简单的代码,但我在哪里可以找到这样的例子?

你可以使用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中这样做,请使用。 context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

Kotlin语法

// Check if no view has focus:
 val view = this.currentFocus
 view?.let { v ->
  val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager 
  imm?.hideSoftInputFromWindow(v.windowToken, 0)
 }
评论(34)

对隐藏软键盘也很有用的是。

getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
);

这可以用来抑制软键盘,直到用户真正触摸到编辑文本视图。

评论(13)

请在 "onCreate() "中尝试下面的代码

EditText edtView=(EditText)findViewById(R.id.editTextConvertValue);
edtView.setInputType(0);
评论(6)