Actually, there is keyboard listener

Sviatoslav Melnychenko
1 min readJun 26, 2018

--

At least if you hide keyboard by yourself

I faced this trouble. When you replace view on your activity and you have EditText with anopened keyboard, sometimes you get exception and crash:

java.lang.NullPointerException: Attempt to invoke interface method 'void android.view.inputmethod.InputConnection.closeConnection()' on a null object reference
at android.view.inputmethod.InputConnectionWrapper.closeConnection(InputConnectionWrapper.java:270

Or, in case of Samsung, keyboard stays on screen and freezes.

As my colleague said, “You can’t fix Android, but you can find a workaround”. An obvious one is to wait, while the keyboard is closed and then do your stuff. There is a great article about utilizing OnGlobalLayoutListener with help of RxJava.

In my case, I could be pro-active and close keyboard by myself. And InputMethodManager has a great method for this:

public boolean hideSoftInputFromWindow (IBinder windowToken, 
int flags,
ResultReceiver resultReceiver)

where the third parameter is our desired listener. I believe it’s straightforward, what’s going next. So, there an extension functions for you:

And here is usage:

nextButton.setOnClickListener {
passwordEditText.hideKeyboard { doStuff()}
}

There is no more crashes or keyboard freezes.

Photo by Markus Gjengaar on Unsplash

--

--