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

car*_*erz 21 android

我有一个EditText控件.如果我点击它,软键盘会弹出,但是当我按下"输入/确定/返回"然后按下EditText控件时它仍然具有焦点和键盘.
如何关闭软键盘并从中移除焦点?

Mit*_*kum 14

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editTextField.getWindowToken(), 0);
Run Code Online (Sandbox Code Playgroud)

  • 这只会隐藏键盘.它不会消除焦点. (2认同)

And*_*rew 11

在布局XML文件中,在EditText上指定imeOption:

android:imeOptions="actionGo"
Run Code Online (Sandbox Code Playgroud)

接下来,在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;
        }
    });
Run Code Online (Sandbox Code Playgroud)

其中mYourEditText是EditText对象


knp*_*wrs 1

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

KeyListener如果您正在谈论键盘本身上的“输入/确定/返回”按钮,您可能必须在控件上设置 ,EditText以便知道何时SetFocus()在另一个元素上。

  • 我知道这是很多人给出的解决方案,但我不喜欢它,因为 input.clearFocus() 不是简单地工作(即从该输入中清除焦点),而是现在必须将焦点设置为其他内容!?这似乎违反直觉。 (2认同)