package com.xxx.xxx.utils
import android.util.Log
import android.view.View
import android.view.Window
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
private val KEYBOARD = WindowInsetsCompat.Type.ime()
private val NAVIGATION_BAR = WindowInsetsCompat.Type.navigationBars()
fun registerKeyboardListener(window: Window?, block: (currentFocusView: View?, imeVisible: Boolean) -> Unit) {
window?.decorView?.rootView?.let { windowView ->
windowView.post {// Add this case there are input comp in 2 consecutive pages(unregisterKeyboardListener method will invoke after the register invoke)
Log.d("KeyboardUtils","KeyboardListener==>register@${windowView.hashCode()}")
val listener = androidx.core.view.OnApplyWindowInsetsListener { view, insets ->
window.currentFocus?.let { currentFocus ->
val imeVisible = insets.isVisible(KEYBOARD)
Log.d("KeyboardUtils","KeyboardListener==>keyboardShown:$imeVisible")
block.invoke(currentFocus, imeVisible)
}
//cannot return insets,must returns as below:
ViewCompat.onApplyWindowInsets(view, insets)
}
ViewCompat.setOnApplyWindowInsetsListener(windowView, listener)
}
}
}
fun unregisterKeyboardListener(window: Window?) {
window?.decorView?.rootView?.let { windowView ->
ViewCompat.setOnApplyWindowInsetsListener(windowView, null)
Log.d("KeyboardUtils","KeyboardListener==>unregister@${windowView.hashCode()}")
}
}
fun getSystemWindow(fragment: Fragment?, isEmbeddedFragment: Boolean = false): Window? {
val windowFragment = if (isEmbeddedFragment) {
fragment?.parentFragment
} else {
fragment
}
val window: Window? = if (windowFragment is DialogFragment) {
windowFragment.dialog?.window
} else {
windowFragment?.activity?.window
}
return window
}
-----------------------------End-----------------------------