How to Check the Visibility of Software Keyboard in Android?
In some cases, we should determine if the keyboard is displayed or not in a given activity. In this example, we can see how to verify the presence of a virtual keyboard on Android. With the release of Android 11 preview 2 and here, it appears that platform behavior for listening to keyboard changes is finally being implemented! This appears to use WindowInsets behind the hood, thus it will most likely be backported to previous versions of Android.
So what’s the issue with the current offering?
You want to know if the Android keyboard is open right now. Isn’t it simple?
No, it does not. The Android keyboard is a fantastic piece of design that manages most of its visibility internally — relying on user input rather than developer input. When it works, it’s a fantastic system…until it doesn’t. Because Android doesn’t give a straightforward means to identify whether the keyboard is open, we’ll have to be a bit creative. The View class includes a useful method called getWindowVisibleDisplayFrame that returns a rectangle containing the section of the view that is visible to the user. This includes system decorations that may be positioned on top of the view (such as the keyboard).
The visible height may be calculated from the visible rectangle. We can tell if the keyboard has been drawn on top of the image by comparing the visible height to the real height of the view. (hint: this may also be used to determine the height of the keyboard.) Then do this:
If the keyboard is visible after pressing the button, we use hideSoftKeyboard to hide it. Finally, launch the application and view the results on your mobile device. In this blog, we learned how to determine whether or not the keyboard is displayed on the screen. We also have how to shut the keyboard if it is visible. That concludes this blog.