3

I want to achieve a simple task of unfocusing EditText (not hide cursor) when keyboard is dismissed, either by hitting the done or the return button. All I can find so far is

window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)

But it is only good when the activity is first opened up. After keyboard is dismissed, text field is left in an awkward focused state.

Jack Guo
  • 2,787
  • 4
  • 23
  • 50

4 Answers4

3

You could listen for an event when keyboard is dismissed and then use editText.clearFocus(); when that event happens.

Refer to this answer for listening to keyboard dismiss events

Jeeter
  • 4,960
  • 3
  • 41
  • 64
Tomas Jablonskis
  • 3,582
  • 4
  • 20
  • 32
2

I can't believe this is the easiest solution I could find to this problem (really, Android?):

public class CustomEditText extends EditText {

    public CustomEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == KeyEvent.KEYCODE_ENDCALL) {
                    InputMethodManager imm = (InputMethodManager)v.getContext()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(CustomEditText.this.getWindowToken(), 0);
                    CustomEditText.this.clearFocus();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            this.clearFocus();
        }
        return super.onKeyPreIme(keyCode, event);
    }

}
Adam Johns
  • 32,040
  • 21
  • 108
  • 161
0

You can clear the focus from edit text and also manage the enable/disable edit text.

Hkh
  • 347
  • 1
  • 9
0

Kotlin version:

class CustomEditText: AppCompatEditText {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)

    override fun onKeyPreIme(keyCode: Int, event: KeyEvent?): Boolean {
        if(keyCode == KeyEvent.KEYCODE_BACK) {
            clearFocus()
        }
        return super.onKeyPreIme(keyCode, event)
    }
}

Usage:

<com.youappdomain.view.CustomEditText
      android:layout_width="match_parent"
      android:layout_height="wrap_content" />
KBog
  • 1,454
  • 19
  • 25