Created
February 8, 2021 06:32
-
-
Save yusufonderd/9e91995c71a60b53b7acd9807bb3226c to your computer and use it in GitHub Desktop.
Keyboard Visibility Status Event Listener
This file contains hidden or 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
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