Android 按下软键盘中的“完成”按钮时,如何失去编辑文本的焦点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11981740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:21:27  来源:igfitidea点击:

How to lose the focus of a edittext when "done" button in the soft keyboard is pressed?

androidandroid-edittextandroid-softkeyboard

提问by SSS

I have 7 edittext boxes in my xml. I'm using the OnFocusChangeListener to read the value from edittext and i'm using that value for my calculation.I want to make my edittext to lose its focus when i click on the done button in the soft keyboard.so that i can get the value in the edittext.

我的 xml 中有 7 个 edittext 框。我正在使用 OnFocusChangeListener 从 edittext 读取值,我正在使用该值进行计算。当我单击软键盘中的完成按钮时,我想让我的编辑文本失去焦点。这样我就可以得到编辑文本中的值。

回答by ρяσ?ρ?я K

Call clearFocusmethod of EditTextto lose focus when done button is clicked from soft-keyboard. do it as:

从软键盘单击完成按钮时调用失去焦点的clearFocus方法EditText。这样做:

editText.setOnEditorActionListener(new OnEditorActionListener() {        
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if(actionId==EditorInfo.IME_ACTION_DONE){
            //Clear focus here from edittext
             editText.clearFocus();
        }
    return false;
    }
});

and also add android:imeOptions="actionDone"in edittext xml

并添加android:imeOptions="actionDone"edittext xml

回答by Julian Declercq

If anyone comes across this question wondering how they could unfocus everything at oncein their activity, they can set the focus on the parent layout(or any layout for that matter).

如果有人遇到这个问题,想知道如何在他们的Activity 中一次性取消所有内容焦点,他们可以将焦点设置在父布局(或任何与此相关的布局)上。

findViewById(R.id.myLayout).requestFocus();

回答by ucMedia

Just a little more complete answer

只是更完整的答案

//  This will change the ‘RETURN' button in your the EditText's soft keyboard to a ‘DONE' button.
editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
//  Use the InputMethodManager to close the soft keyboard
editText.setOnEditorActionListener(new OnEditorActionListener() {        
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if(actionId==EditorInfo.IME_ACTION_DONE){
            //Clear focus here from edittext
            InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    return false;
    }
});

回答by norbDEV

Kotlin, it worked for me:

Kotlin,它对我有用:

main.clearFocus()

main is a root ConstraintLayout

main 是一个根 ConstraintLayout