How to Check Visibility of Software Keyboard in Android

How to Check Visibility of Software Keyboard in Android

6 June 2024 Stephan Petzl Leave a comment Tech-Help

Detecting whether the software keyboard is visible in an Android application can be a crucial aspect of ensuring a smooth user experience. This guide provides a practical approach to determine the visibility of the software keyboard in Android.

Solution Using ViewTreeObserver and GlobalLayoutListener

One of the most effective methods to check if the software keyboard is shown is by using the ViewTreeObserver and GlobalLayoutListener. This approach involves calculating the difference in height between the root view of the activity and the window size.

Step-by-Step Implementation

  1. First, assign a known ID to your activity’s root view in your layout file:

    <View
        android:id="@+id/activityRoot"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </View>
  2. Then, in your activity class, add a GlobalLayoutListener to the root view’s ViewTreeObserver:

    final View activityRootView = findViewById(R.id.activityRoot);
    activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
            if (heightDiff > dpToPx(this, 200)) { // if more than 200 dp, it's probably a keyboard...
                // Keyboard is visible
            } else {
                // Keyboard is hidden
            }
        }
    });
  3. Utilize a utility method to convert dp to pixels:

    public static float dpToPx(Context context, float valueInDp) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics);
    }

Important Note

Ensure that your application sets the following flag in the Android Manifest:

<activity
    android:windowSoftInputMode="adjustResize">
</activity>

Enhanced Approach for AdjustPan

If your application uses adjustPan instead of adjustResize, you can modify the above approach slightly to account for this. By checking the height difference in a different manner, you can still determine the visibility of the keyboard:

final View activityRootView = findViewById(R.id.activityRoot);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        Rect r = new Rect();
        activityRootView.getWindowVisibleDisplayFrame(r);
        int heightDiff = activityRootView.getRootView().getHeight() - r.height();
        if (heightDiff > 0.25 * activityRootView.getRootView().getHeight()) { // if more than 25% of the screen, it's probably a keyboard...
            // Keyboard is visible
        } else {
            // Keyboard is hidden
        }
    }
});

Utilizing Modern APIs

With recent updates to the Android API, you can now use more straightforward methods to check for keyboard visibility. These methods are part of the ViewCompat and WindowInsetsController introduced in API 30 (Android 11):

Check Keyboard Visibility

val insets = ViewCompat.getRootWindowInsets(view)
val isKeyboardVisible = insets.isVisible(Type.ime())

Get Keyboard Height

val insets = ViewCompat.getRootWindowInsets(view)
val keyboardHeight = insets.getInsets(Type.ime()).bottom

Show/Hide Keyboard

val controller = view.windowInsetsController
// Show the keyboard
controller.show(Type.ime())
// Hide the keyboard
controller.hide(Type.ime())

These methods provide a more reliable and modern approach to handling keyboard visibility in Android applications.

Conclusion

By using the methods outlined above, you can effectively determine the visibility of the software keyboard in your Android application. This can significantly enhance the user experience by allowing you to adjust your UI elements accordingly.

Enhance Your Testing with Repeato

Ensuring that your application handles keyboard visibility correctly is essential for a smooth user experience. To streamline your testing process, consider using Repeato. Repeato is a No-code test automation tool for iOS and Android that helps you create, run, and maintain automated tests for your apps. Its efficient use of computer vision and AI allows you to quickly edit and run tests, freeing up your time to focus on creating a great product.

Repeato’s intuitive interface also allows non-technical colleagues or QA teams to take on the task of test automation, ensuring that your application is thoroughly tested without requiring extensive technical expertise. Learn more about how Repeato can assist with your mobile testing needs by visiting our documentation or contacting us.

Like this article? there’s more where that came from!