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

在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?


当前回答

如果要使用Java代码隐藏键盘,请使用以下命令:

  InputMethodManager imm = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
  imm.hideSoftInputFromWindow(fEmail.getWindowToken(), 0);

或者,如果您希望始终隐藏键盘,请在AndroidManifest中使用此选项:

 <activity
 android:name=".activities.MyActivity"
 android:configChanges="keyboardHidden"  />

其他回答

在AndroidManifest.xml中的<activity..>set android:windowSoftInputMode=“stateAlwaysHidden”

只需在活动中使用此优化代码:

if (this.getCurrentFocus() != null) {
    InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}

以下是最佳解决方案

解决方案1)将inputType设置为“text”

<EditText
android:id="@+id/my_edit_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Tap here to type"
android:inputType="text" />

这也可以通过编程实现。方法setInputType()(从TextView继承)。

EditText editText = (EditText) findViewById(R.id.my_edit_text);
editText.setRawInputType(InputType.TYPE_CLASS_TEXT | 
InputType.TYPE_TEXT_VARIATION_NORMAL);

解决方案2)使用InputMethodManager.hideSoftInputFromWindow()

InputMethodManager imm = 
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

or

InputMethodManager imm = (InputMethodManager) 
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 
InputMethodManager.HIDE_NOT_ALWAYS);

Kotlin版本

val imm: InputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
//Hide:
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
//Show
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);

这对我有用。。

EditText editText=(EditText)findViewById(R.id.edittext1);

放在onClick()中的代码行下面

editText.setFocusable(false);
editText.setFocusableInTouchMode(true);

这里隐藏键盘,当我们单击按钮时,当我们触摸EditText键盘时,将显示。

(OR)

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