An Android sample project demonstrating how to calculate the height of a floating soft keyboard.
KeyboardHeightProvider uses a hidden PopupWindow sized to the full height of the activity window. Because the popup is configured with SOFT_INPUT_ADJUST_RESIZE, it shrinks when the soft keyboard appears. By comparing the popup's visible area to the screen height, the keyboard height can be derived and reported to any registered KeyboardHeightObserver.
- Instantiate
KeyboardHeightProviderin your activity'sonCreate. - Call
start()after the activity's root view has been laid out (e.g. viaview.post(...)). - Register an observer in
onResumeand unregister inonPause. - Close the provider in
onDestroy.
keyboardHeightProvider = new KeyboardHeightProvider(this);
view.post(() -> keyboardHeightProvider.start());
// onResume
keyboardHeightProvider.setKeyboardHeightObserver(this);
// onPause
keyboardHeightProvider.setKeyboardHeightObserver(null);
// onDestroy
keyboardHeightProvider.close();Implement KeyboardHeightObserver to receive height changes:
@Override
public void onKeyboardHeightChanged(int height, int orientation) {
// height is 0 when the keyboard is closed
}Since Android 11 (API 30) the platform provides a first-class API for keyboard height detection. If you are targeting API 30 or higher, consider using:
WindowInsetsCompat.Type.ime()— returns the keyboard height once fully shown or hidden.ViewCompat.setWindowInsetsAnimationCallback()— provides per-frame inset values during the open/close animation, useful for animating UI elements alongside the keyboard.
Both require WindowCompat.setDecorFitsSystemWindows(window, false) on the activity window.
- Min SDK: 21
- Target SDK: 36 (Android 16)
- AndroidX
Lesser GNU General Public License v3. See source file headers for details.