简体   繁体   English

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

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

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 中读取值,我正在使用该值进行计算。我想让我的 edittext 在单击完成按钮时失去焦点软键盘。这样我就可以在编辑文本中获取值。

Call clearFocus method of EditText to lose focus when done button is clicked from soft-keyboard.从软键盘单击完成按钮时,调用EditText clearFocus方法以失去焦点。 do it as:这样做:

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并在 edittext xml 中添加android:imeOptions="actionDone"

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

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

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;
    }
});

Kotlin, it worked for me: Kotlin,它对我有用:

main.clearFocus()

main is a root ConstraintLayout main 是一个根 ConstraintLayout

Kotlin version of ρяσѕρєя K's answer: Kotlin 版本的 ρяσѕρєя K 的回答:

editText.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        editText.clearFocus()
    }
    false
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM