Updated on 2026-08-14

This commit is contained in:
Tangem 2020-09-08 15:50:55 +03:00
parent 9b3f6994a9
commit 98ea9b0ead
25 changed files with 648 additions and 88 deletions

View file

@ -0,0 +1,61 @@
package com.tangem.tap.common
import android.app.Activity
import android.graphics.Rect
import android.util.DisplayMetrics
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import kotlin.math.absoluteValue
class KeyboardObserver(activity: Activity) {
private val decorView = activity.window.decorView
private val windowManager = activity.windowManager
private val originalWindowHeight: Int = getWindowHeight()
private val onGlobalLayoutListener: OnGlobalLayoutListener = OnGlobalLayoutListener { onGlobalLayout() }
private var onKeyboardListener: ((Boolean) -> Unit)? = null
private var lastIsShow = false
private var lastWindowHeight = getWindowHeight()
fun registerListener(listener: (Boolean) -> Unit) {
decorView.viewTreeObserver.addOnGlobalLayoutListener(onGlobalLayoutListener)
onKeyboardListener = listener
}
fun unregisterListener() {
decorView.viewTreeObserver.removeOnGlobalLayoutListener(onGlobalLayoutListener)
onKeyboardListener = null
}
private fun getWindowHeight() = Rect().apply { decorView.getWindowVisibleDisplayFrame(this) }.bottom
private fun onGlobalLayout() {
val currentWindowHeight = getWindowHeight()
if (isSoftKeyChanged()) {
lastWindowHeight = currentWindowHeight
return
}
lastWindowHeight = currentWindowHeight
val isShow = originalWindowHeight != currentWindowHeight
if (lastIsShow == isShow) return
lastIsShow = isShow
onKeyboardListener?.invoke(isShow)
}
private fun isSoftKeyChanged() = ((lastWindowHeight - getWindowHeight()).absoluteValue) == getSoftKeyButtonHeight()
private fun getSoftKeyButtonHeight(): Int {
val applicationDisplayHeight = DisplayMetrics().apply {
windowManager.defaultDisplay.getMetrics(this)
}.heightPixels
val realDisplayHeight = DisplayMetrics().apply {
windowManager.defaultDisplay.getRealMetrics(this)
}.heightPixels
return realDisplayHeight - applicationDisplayHeight
}
}