Open In App

How to Check the Visibility of Software Keyboard in Android?

Improve
Improve
Like Article
Like
Save
Share
Report

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).

Kotlin




val keyboardVisible = Rect()
someRandomView.getWindowVisibleDisplayFrame(keyboardVisible)


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:

Java




if (oldAltitude < newAltitude) {
    if (keyboardVisibleState) {
            keyboardVisibleState = false;
            stopNav();
    if (keyboardChecker != null) {
            keyboardChecker.onKeyboardHidden();
        }
    } else if (oldAltitude > newAltitude) {
            InputMethodManager gfg = (InputMethodManager) mContentView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            boolean isAcceptingText = gfg.isAcceptingText();
if (isAcceptingText) {
        keyboardVisibleState = true;
    }
if (keyboardVisibleState) {
    if (keyboardChecker != null) {
            keyboardChecker.onKeyboardVisible();
            }
        }
    }
}


Conclusion

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.



Last Updated : 08 Sep, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads