Detecting when the soft keyboard is present

Hello fellow newbie Android dev! :)

Today, I want to share with you a small snipped of code which will help you to detect when the soft keyboard is shown in your activity and updated the UI to adapt.

The case I had was to resize the RecyclerView, scroll to the last position and move the EditText on top of the soft keyboard.

So here are the steps:

STEP 1

First of all you have to declare in your activity's declaration in the AndroidManifest that you want the windowSoftInputMode to be adjustResize:
<activity android:name=".HomeActivity" android:windowSoftInputMode="adjustResize"/>

This will allow the system to resize the activity accordingly when the soft keyboard has been shown instead of placing it over the activity which is the default behavior.

STEP 2

In your HomeActivity you should get a reference to it's root layout and add a OnGlobalLayoutListener to its viewTreeObserver where the magic will happen.

val rootView: ViewGroup = findViewById(android.R.id.content)
rootView.viewTreeObserver.addOnGlobalLayoutListener {
  val r = Rect()
  rootView.getWindowVisibleDisplayFrame(r);

  val heightDiff = rootView.rootView.height - (r.bottom - r.top);
  if (heightDiff > rootView.rootView.height / 4) {
    // THE SOFT KEYBOARD IS VISIBLE. UPDATE YOUR LAYOUT HERE
  }
}

Maybe you're wondering why we have this:
if (heightDiff > rootView.rootView.height / 4)

This is a better way of telling if the soft keyboard is visible on most of the devices - from these with small screens to the ones with large screens.

Conclusion

That's it all! So simple, isn't it? 👻