EditText Clear Focus On Keyboard Hidden (Kotlin)

Apr 20, 2018

For this to work, you would need to subclass EditText, preferbly AppCompatEditText.

When back key is pressed (hide the keyboard), execute code to clear focus.

class ClearFocusEditText: 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)    }}
<com.mydomain.myapp.view.ClearFocusEditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

This is useful for scenario where android:windowSoftInputMode="adjustPan" doesn't work properly the second time (after keyboard hidden from the first time).

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.