Skip to content

Instantly share code, notes, and snippets.

@yusufonderd
Created February 8, 2021 06:32
Show Gist options
  • Save yusufonderd/9e91995c71a60b53b7acd9807bb3226c to your computer and use it in GitHub Desktop.
Save yusufonderd/9e91995c71a60b53b7acd9807bb3226c to your computer and use it in GitHub Desktop.
Keyboard Visibility Status Event Listener
import android.view.View
import android.view.ViewTreeObserver
import androidx.fragment.app.FragmentActivity
private const val RATIO_KEYBOARD_VISIBILITY = 0.25
object KeyboardVisibilityEvent {
private var isKeyboardShowing = false
private var globalLayoutListener: ViewTreeObserver.OnGlobalLayoutListener? = null
fun registerEventListener(activity: FragmentActivity?,
keyboardStatus: (isOpen: Boolean) -> Unit) {
unRegisterEventListener(activity)
activity?.findViewById<View>(android.R.id.content)?.let { activityRootView ->
globalLayoutListener = ViewTreeObserver.OnGlobalLayoutListener {
val rect = Rect().apply { activityRootView.getWindowVisibleDisplayFrame(this) }
val heightRootView = activityRootView.rootView.height
val heightDiff = heightRootView - rect.height()
if (heightDiff > RATIO_KEYBOARD_VISIBILITY * heightRootView) {
if (!isKeyboardShowing) {
isKeyboardShowing = true
keyboardStatus(true)
}
} else {
if (isKeyboardShowing) {
isKeyboardShowing = false
keyboardStatus(false)
}
}
}
activityRootView.viewTreeObserver.addOnGlobalLayoutListener(globalLayoutListener)
}
}
fun unRegisterEventListener(activity: FragmentActivity?) {
globalLayoutListener?.let {
activity?.findViewById<View>(
android.R.id.content)?.viewTreeObserver?.removeOnGlobalLayoutListener(
globalLayoutListener)
globalLayoutListener = null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment