Created
March 2, 2022 10:30
-
-
Save Schadenfeude/cb5da5c28832f53e37b24299a9182e3f to your computer and use it in GitHub Desktop.
Provides the height of the keyboard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class KeyboardHeightProvider(activity: Activity) : PopupWindow(activity), | |
OnGlobalLayoutListener { | |
private val mActivity: Activity = activity | |
private val rootView: View = View(activity) | |
// Record the maximum height of the pop content area | |
private var heightMax = 0 | |
private val mutHeightChanged = MutableStateFlow(0) | |
val onHeightChanged: StateFlow<Int> = mutHeightChanged | |
init { | |
// Basic configuration | |
contentView = rootView | |
// Monitor global Layout changes | |
rootView.viewTreeObserver.addOnGlobalLayoutListener(this) | |
setBackgroundDrawable(ColorDrawable(0)) | |
// Set width to 0 and height to full screen | |
width = 0 | |
height = LayoutParams.MATCH_PARENT | |
// Set keyboard pop-up mode | |
softInputMode = LayoutParams.SOFT_INPUT_ADJUST_RESIZE | |
inputMethodMode = INPUT_METHOD_NEEDED | |
if (!isShowing) { | |
val view: View = mActivity.window.decorView | |
// Delay loading popup window, if not, error will be reported | |
view.post { showAtLocation(view, Gravity.NO_GRAVITY, 0, 0) } | |
} | |
} | |
override fun onGlobalLayout() { | |
val rect = Rect() | |
rootView.getWindowVisibleDisplayFrame(rect) | |
if (rect.bottom > heightMax) heightMax = rect.bottom | |
// The difference between the two is the height of the keyboard | |
val keyboardHeightPx = heightMax - rect.bottom | |
// Return rect.bottom if you just need the coordinates of the current bottom of the screen | |
mutHeightChanged.value = keyboardHeightPx.toDp | |
} | |
private val Int.toDp get() = (this / Resources.getSystem().displayMetrics.density).toInt() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: If this doesn't work as is, you need to add:
To your
AndroidManifest.xml