如何在API 19中使用WindowInsetsCompat API判断软键盘可见性?
Solution for Checking Soft Keyboard Visibility with minSdk 19
Hey there! Since your project targets minSdk 19 and you're hitting limitations with WindowInsetsCompat on older APIs, here's a comprehensive, reliable approach that works across all your supported versions—tailored to your activity's window soft input mode:
1. When using adjustResize window mode
This mode plays nicely with both modern and legacy checks:
- API 23+: Stick with the
WindowInsetsCompatmethod you initially found—it’s fully reliable here - API <23: Fall back to layout change detection.
adjustResizeforces the root view to shrink when the keyboard appears, so we can compare the view's visible frame to the total screen height to spot the keyboard.
Code Example for adjustResize
fun isKeyboardVisible(view: View): Boolean { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val insets = ViewCompat.getRootWindowInsets(view) insets?.isVisible(WindowInsetsCompat.Type.ime()) == true } else { // Fallback for older APIs val visibleFrame = Rect() view.getWindowVisibleDisplayFrame(visibleFrame) val totalScreenHeight = view.rootView.height val keyboardHeight = totalScreenHeight - visibleFrame.bottom // Consider keyboard visible if it covers >15% of the screen (adjust threshold as needed) keyboardHeight > totalScreenHeight * 0.15 } }
2. When using adjustPan window mode
As you noted, this mode works reliably with IME inset checks starting from API 14. We can use the compatibility OnApplyWindowInsetsListener to listen for keyboard visibility changes across all your target versions:
Code Example for adjustPan
fun setupKeyboardVisibilityListener(view: View, onKeyboardStateChanged: (Boolean) -> Unit) { ViewCompat.setOnApplyWindowInsetsListener(view) { _, insets -> val isKeyboardVisible = insets.isVisible(WindowInsetsCompat.Type.ime()) onKeyboardStateChanged(isKeyboardVisible) insets // Pass insets through to continue default handling } // Trigger an initial check immediately ViewCompat.requestApplyInsets(view) }
Key Tips
- Match your approach to your activity's window soft input mode for the best reliability
- The 15% threshold in the legacy fallback is flexible—tweak it if your UI has unusual bottom-aligned elements
- If using layout change listeners (for adjustResize on API <23), remember to unregister them when the view is destroyed to avoid memory leaks
内容的提问来源于stack exchange,提问作者Arpit Shukla
相关产品推荐
相关产品推荐

