-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKeyboardVisibilityObserver.kt
More file actions
40 lines (36 loc) · 1.36 KB
/
KeyboardVisibilityObserver.kt
File metadata and controls
40 lines (36 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.google.ai.sample
import android.graphics.Rect
import android.util.Log
import android.view.View
import android.view.ViewTreeObserver
import kotlinx.coroutines.flow.MutableStateFlow
internal class KeyboardVisibilityObserver(
private val tag: String
) {
private var onGlobalLayoutListener: ViewTreeObserver.OnGlobalLayoutListener? = null
fun start(rootView: View, keyboardState: MutableStateFlow<Boolean>) {
stop(rootView)
onGlobalLayoutListener = ViewTreeObserver.OnGlobalLayoutListener {
val rect = Rect()
rootView.getWindowVisibleDisplayFrame(rect)
val screenHeight = rootView.rootView.height
val keypadHeight = screenHeight - rect.bottom
if (keypadHeight > screenHeight * 0.15) {
if (!keyboardState.value) {
keyboardState.value = true
Log.d(tag, "Keyboard visible")
}
} else if (keyboardState.value) {
keyboardState.value = false
Log.d(tag, "Keyboard hidden")
}
}
rootView.viewTreeObserver.addOnGlobalLayoutListener(onGlobalLayoutListener)
}
fun stop(rootView: View) {
onGlobalLayoutListener?.let {
rootView.viewTreeObserver.removeOnGlobalLayoutListener(it)
}
onGlobalLayoutListener = null
}
}