如何清除焦点和删除Android上的键盘?

我有一个EditText控件。 如果我点击它,softkeyboard会popup,但是当我按“enter / ok / return”,然后EditText控件它仍然有焦点和键盘。
如何关闭软键盘并从中删除焦点?

您可以尝试在布局中的另一个元素上执行SetFocus()

如果您正在讨论键盘上的“enter / ok / return”按钮,您可能需要在EditText控件上设置一个KeyListener ,以便知道何时在另一个元素上使用SetFocus()

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

在布局XML文件中,在EditText上指定一个ime选项:

 android:imeOptions="actionGo" 

接下来,在Activity的java文件中添加一个动作监听器给你的EditText

  mYourEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_GO) { // hide virtual keyboard InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mYourEditText.getWindowToken(), 0); return true; } return false; } }); 

其中mYourEditText是一个EditText对象

 private void hideDefaultKeyboard() { activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); //you have got lot of methods here } 

确保您的EditText XML具有:

 android:id="@+id/myEditText" android:imeOptions="actionDone" 

然后将监听器设置为您的EditText(使用Kotlin和片段):

 myEditText.setOnEditorActionListener({ v, actionId, event -> if (actionId == EditorInfo.IME_ACTION_DONE) { myEditText.clearFocus() val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view!!.windowToken, 0) } false })