项目中遇到的一个问题,
解放方法:https://blog.csdn.net/qq_34161388/article/details/89101442,感觉博主的实践。
import android.R
import android.app.Activity
import android.graphics.Rect
import android.os.Build
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.FrameLayout
class SoftHideKeyBoardUtil(activity: Activity) {
companion object {
@JvmStatic
fun assistActivity(activity: Activity) {
SoftHideKeyBoardUtil(activity)
}
@JvmStatic
fun hideKeyboard(act: Activity?) {
if (act != null && act.currentFocus != null) {
val inputMethodManager = act.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(act.currentFocus.windowToken, 0)
}
}
}
private var mContentView: View? = null
private var mFrameLayoutParams: FrameLayout.LayoutParams? = null
private var barStatusHeight = 0
private var lastUsableHeight = 0 //上一次的可用高度
init {
barStatusHeight = statusBarHeight
val decorView = activity.findViewById<FrameLayout>(R.id.content)
mContentView = decorView.getChildAt(0)
mFrameLayoutParams = mContentView?.layoutParams as? FrameLayout.LayoutParams
mContentView?.viewTreeObserver?.addOnGlobalLayoutListener {
val heightDecor = decorView.height
val usableHeight = computeUsableHeight() //我们setContentView设置的view的可用高度
if (usableHeight != lastUsableHeight) {
lastUsableHeight = usableHeight //防止重复变动
val heightDifference = heightDecor - usableHeight
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && activity.isInMultiWindowMode) { //如果是分屏模式
if (heightDifference > 0) { //分屏模式,只要变动了就人为弹出键盘
setHeight(heightDecor - heightDifference) //这里不能加状态栏高度,因为不知道应用是在上还是下
} else {
setHeight(FrameLayout.LayoutParams.MATCH_PARENT)
}
} else {
if (heightDifference > heightDecor / 4) { //高度变动超过decor的四分之一则认为是软键盘弹出事件
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setHeight(heightDecor - heightDifference + barStatusHeight) // 沉浸式要加上状态栏高度
} else {
setHeight(heightDecor - heightDifference)
}
} else {
setHeight(FrameLayout.LayoutParams.MATCH_PARENT)
}
}
}
}
}
private fun setHeight(height: Int) {
if (mFrameLayoutParams?.height != height) { //不必要的更新就不要了
mFrameLayoutParams?.height = height
mContentView?.requestLayout() //触发布局更新
}
}
private fun computeUsableHeight(): Int {
val r = Rect()
mContentView?.getWindowVisibleDisplayFrame(r)
return r.bottom - r.top
}
}