简体   繁体   中英

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.

Call clearFocus method of EditText to lose focus when done button is clicked from soft-keyboard. 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

如果有人遇到这个问题,想知道如何在他们的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:

main.clearFocus()

main is a root ConstraintLayout

Kotlin version of ρяσѕρєя K's answer:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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