SSS
SSS

Reputation: 693

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.

Upvotes: 31

Views: 28175

Answers (5)

krichards
krichards

Reputation: 41

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

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

Upvotes: 1

norbDEV
norbDEV

Reputation: 5365

Kotlin, it worked for me:

main.clearFocus()

main is a root ConstraintLayout

Upvotes: 0

ucMax
ucMax

Reputation: 5478

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

Upvotes: 0

Julian Declercq
Julian Declercq

Reputation: 1596

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

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

Upvotes: 2

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132992

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

Upvotes: 79

Related Questions