Here is a simple adaptation from some answers above in a Kotlin implementation. It requires as mentioned above windowsSoftInput="adjustResize" in the manifest:
class KeyboardWatcher(private val layoutRooView: View) {
companion object {
private const val MIN_KEYBOARD_HEIGHT = 200f
}
private val displayMetrics: DisplayMetrics = layoutRooView.resources.displayMetrics
private var stateVisible = false
var observer: ((Boolean) -> Unit)? = null
init {
layoutRooView.viewTreeObserver.addOnGlobalLayoutListener {
val heightDiff = layoutRooView.rootView.height - layoutRooView.height
if (!stateVisible && heightDiff > dpToPx(MIN_KEYBOARD_HEIGHT)) {
stateVisible = true
observer?.invoke(stateVisible)
} else if(stateVisible) {
stateVisible = false
observer?.invoke(stateVisible)
}
}
}
private fun dpToPx(valueInDp: Float): Float {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, displayMetrics)
}
}
And to use:
val activityRootView = findViewById<ViewGroup>(R.id.activityRoot)
KeyboardWatcher(activityRootView).observer = { visible ->
if (visible) do something here ...
}