Android R is also known as Android 11 release brought a few new APIs to the table and one of them is the new WindowInset which expands the control that we as developers have over the window insets. This includes the navigation and status bar as well as an on-screen keyboard.
This new release provides a direct way to check these state changes that now toggle and listen for changes in the visibility of the window insets. These options now allow the developer to control and react to the animation when the visibility state changes (but this is not going to be covered within this article).
Getting Started
When writing this post, Android 11 been running on more than 1% of devices, but thanks to the magic of AndroidX the APIs are also usable on several other devices with earlier versions. This post focus on using AndroidX implementation but you will find the equivalent APIs to use in documentation.
implementation "androidx.core:core-ktx:1.5.0-alpha05
Now we are going to insert the following code into the build.gradle file, under all the dependencies. (Note: Any version of 1.5.0 or later will work and please check for the latest version. Apply accordingly)
Show/Hide Keyboard
To start we need to access the WindowInsetsController. When the view is passed it doesn’t have to be an EditText directly but can be any view in the same hierarchy as the focused editText.
//note: ci is my shorthand for controllerInsets val ci = ViewCompat.getWindowInsetsController(view)
Now that we have initialized the view let show the keyboard on the screen:
ci?.show(WindowInsetsCompat.Type.ime())
Let’s hide the keyboard now:
ci?.hide(WindowInsetsCompat.Type.ime())
Keyboard Visibility
If you have ever tried to check the keyboard visibility in the past then you have probably messed with the global layout listeners because there was no other way. Well, hold on to your trousers because finally there is a proper way to do it.
//start by accessing the root window insets val insets = ViewCompat.getRootWindowInsets(view) //Now check the visibility of the IME window insets?.isVisible(WindowInsetsCompat.Type.ime())
Catching Keyboard Changes
To catch the changes with the keyboard visibility, then we have to let the device know that the app is now responsible for the content view of the insets.
//add the following now WindowCompat.setDecorFitsSystemWindows(window, false)
This will force the view to be drawn behind the on-screen keyboard as well as other system UI, however, now that we are listening for the keyboard changes we can move any other conflicting views accordingly.
Conclusion
Controlling the on-screen keyboard is common in Android development, so the APIs are long overdue. Understand that this now provides us (developers) a more reliable and efficient way to control any type of window insets going forward. Also, note that AndroidX allows us to use these APIs with older Android versions as well.