Animating Keyboard Appearance in Android Application

Purpose
Android is more than 10 years old now and still appearance of the soft keyboard resizes application’s content without any animation. As Android engineers at Nullgravity, we wanted to fix this. So, we started with reviewing existing solutions, but all of them involved ViewTreeObserver
and we decided to create our own solution.
Identifying the issue
If we want the system to resize our layout to the available space when the soft keyboard is shown, we have to set SOFT_INPUT_ADJUST_RESIZE
as soft input mode for our window. In this case, Android system will dispatch WindowInsets
to views to notify them about size changes. Usually, the system handles insets just by adding bottom margin to the content view (Window.ID_ANDROID_CONTENT)
. So, how can we animate or intercept this?
Animating Keyboard Appearance
We wanted something with a simple and understandable interface, so we created base class:
We delegated all the logic to View.OnApplyWindowInsetsListener
and forced SOFT_INPUT_ADJUST_RESIZE
as soft input mode for window in order to get proper insets.
The next step, actually, is animating the soft keyboard appearance. The easiest way is to use TransitionManager
and begin delayed transition before the system adjusts the views:
Usage
In Activity:
In BottomSheetDialog:
Result:

But what if we want to have more control over the animation?
Customizable behavior
For example, we want to elevate the content without BottomNavigationView. In this case we need to get keyboard’s height and take control over the process. We can do this using View.OnApplyWindowInsetsListener
once again:
Here we have a bit complicated logic because of devices with hideable navigation bar, but, in general, this code detects offset changes and passes them to onOffsetChanged
. If offset was handled in onOffsetChanged
, we consume it. Otherwise, we let the system to consume it.
Let’s extend BaseKeyboardAnimator one more time:
Now we can implement Animator
with any logic we want:
We have to change one line in out activity to see results:
Result:

We can see some extra padding but this can be easily fixed by subtracting BottomNavigationView height from offset.
Conclusion
As you can see, handling keyboard appearance with animation isn’t so hard. You can find the sample app and source code for the library and many more here. Thank you for reading our story.
If you liked this article, be sure to 👏 and share this article on social media.