Android 键盘检测工具类(从API 1开始适配)

Android 11之前一直没有比较直接的键盘检测方案。提供一个工具类屏蔽这些细节,快速获取键盘高度。
Android 11 提供了动画监听API,可以使用followKeyBoard参数来调用,实现跟随键盘运动的动画。

直接获取键盘高度(兼容到API 21)

import android.os.Build
import android.view.View
import androidx.annotation.RequiresApi
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsAnimationCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver

/**
 * 键盘检测工具类,可观察软键盘的展开和收起。
 * @param followKeyBoard 键盘高度多次触发回调,可以使页面跟随键盘。API30及以上并且设置[WindowCompat.setDecorFitsSystemWindows(window, false)]才可用。当该值为true时,[onKeyHeightListener]在键盘弹出时会触发多次true。
 */
class KeyboardHelper(
    view: View,
    lifecycle: Lifecycle,
    followKeyBoard: Boolean = true
) {
    
    
    private val impl: Impl = if (followKeyBoard && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
        Impl30()
    else
        Impl21()

    val keyBoardHeight: Int
        get() = impl.keyBoardHeight

    var onKeyHeightListener: (keyBoardHeight: Int) -> Unit = {
    
    }

    val isKeyboardShow: Boolean
        get() = keyBoardHeight != 0

    var onKeyBoardShowListener: (isKeyboardShow: Boolean) -> Unit = {
    
    }

    private val listener: (keyboardHeight: Int) -> Unit = {
    
    
        onKeyBoardShowListener(isKeyboardShow)
        onKeyHeightListener.invoke(keyBoardHeight)
    }

    private val lifeObserver = LifecycleEventObserver {
    
     _, event ->
        when (event) {
    
    
            Lifecycle.Event.ON_START -> impl.setCallBack(view, listener)
            Lifecycle.Event.ON_STOP -> impl.removeCallBack(view)
            else -> {
    
    }
        }
    }

    init {
    
    
        lifecycle.addObserver(lifeObserver)
    }

    @RequiresApi(api = Build.VERSION_CODES.R)
    private class Impl30 : Impl {
    
    
        override var keyBoardHeight: Int = 0

        override fun setCallBack(view: View, listener: (keyboardHeight: Int) -> Unit) {
    
    
            ViewCompat.setWindowInsetsAnimationCallback(view,
                object : WindowInsetsAnimationCompat.Callback(DISPATCH_MODE_STOP) {
    
    
                    override fun onProgress(
                        windowInsets: WindowInsetsCompat,
                        runningAnimations: MutableList<WindowInsetsAnimationCompat>
                    ): WindowInsetsCompat {
    
    
                        val imeHeight = windowInsets.getInsets(WindowInsetsCompat.Type.ime()).bottom
                        keyBoardHeight = imeHeight
                        listener.invoke(imeHeight)
                        return windowInsets
                    }
                })
        }

        override fun removeCallBack(view: View) {
    
    
            view.setWindowInsetsAnimationCallback(null)
        }
    }

    private class Impl21 : Impl {
    
    
        override var keyBoardHeight: Int = 0
        override fun setCallBack(view: View, listener: (keyboardHeight: Int) -> Unit) {
    
    
            val callback = {
    
     _: View, insets: WindowInsetsCompat ->
                val imeHeight = insets.getInsets(WindowInsetsCompat.Type.ime()).bottom
                keyBoardHeight = imeHeight
                listener.invoke(imeHeight)
                insets
            }

            ViewCompat.setOnApplyWindowInsetsListener(view, callback)
        }

        override fun removeCallBack(view: View) {
    
    
            ViewCompat.setOnApplyWindowInsetsListener(view, null)
        }
    }

    private interface Impl {
    
    
        var keyBoardHeight: Int
        fun setCallBack(view: View, listener: (keyboardHeight: Int) -> Unit)
        fun removeCallBack(view: View)
    }
}

获取键盘高度+导航栏高度(兼容到API 1)

由于API限制,只能统一获取键盘高度+导航栏,可以再封装一层,减去导航栏高度即可。

package com.gearup.basic.util

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Point
import android.graphics.Rect
import android.os.Build
import android.view.View
import android.view.ViewTreeObserver
import android.view.WindowManager
import androidx.annotation.RequiresApi
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsAnimationCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import kotlin.math.abs

/**
 * 键盘观察者,由于API限制,所以不能直接获取键盘高度
 * @param [followKeyBoard] 键盘高度多次触发回调,可以使页面跟随键盘。API30及以上并且设置[WindowCompat.setDecorFitsSystemWindows(window, false)]才可用。
 *
 * 注:[listener]的高度是导航栏+键盘高度
 */
class KeyboardObserver(
    private val view: View,
    lifecycle: Lifecycle,
    followKeyBoard: Boolean = true,
    private val listener: (navAndKeyBoardHeight: Int) -> Unit
) {
    
    

    private val impl: Impl = if (followKeyBoard && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
    
    
        Impl30()
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    
    
        Impl21()
    } else {
    
    
        Impl1()
    }


    private val lifeObserver = LifecycleEventObserver {
    
     _, event ->
        when (event) {
    
    
            Lifecycle.Event.ON_START -> impl.setCallBack(view, listener)
            Lifecycle.Event.ON_STOP -> impl.removeCallBack(view)
            else -> {
    
    }
        }
    }

    init {
    
    
        lifecycle.addObserver(lifeObserver)
    }

    /**
     * 导航栏和键盘总高度
     */
    val navAndKeyBoardHeight
        get() = impl.navAndKeyBoardHeight

    @RequiresApi(api = Build.VERSION_CODES.R)
    private class Impl30 : Impl {
    
    
        override var navAndKeyBoardHeight: Int = 0

        override fun setCallBack(view: View, listener: (keyboardHeight: Int) -> Unit) {
    
    
            ViewCompat.setWindowInsetsAnimationCallback(view,
                object : WindowInsetsAnimationCompat.Callback(DISPATCH_MODE_STOP) {
    
    
                    override fun onProgress(
                        windowInsets: WindowInsetsCompat,
                        runningAnimations: MutableList<WindowInsetsAnimationCompat>
                    ): WindowInsetsCompat {
    
    
                        val imeHeight = windowInsets.getInsets(WindowInsetsCompat.Type.ime()).bottom
                        val navHeight =
                            windowInsets.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom
                        //imeHeight范围从0开始,为了统一回调,以navHeight为最小值
                        val realHeight = maxOf(imeHeight, navHeight)
                        if (realHeight != navAndKeyBoardHeight) {
    
    
                            navAndKeyBoardHeight = realHeight
                            listener.invoke(realHeight)
                        }
                        return windowInsets
                    }
                })
        }

        override fun removeCallBack(view: View) {
    
    
            view.setWindowInsetsAnimationCallback(null)
        }
    }

    @SuppressLint("ObsoleteSdkInt")
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private class Impl21 : Impl {
    
    
        override var navAndKeyBoardHeight: Int = 0
        override fun setCallBack(view: View, listener: (keyboardHeight: Int) -> Unit) {
    
    
            val callback = {
    
     _: View, insets: WindowInsetsCompat ->
                val imeHeight = insets.getInsets(WindowInsetsCompat.Type.ime()).bottom
                val navHeight = insets.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom
                val realHeight = imeHeight + navHeight
                navAndKeyBoardHeight = realHeight
                listener.invoke(realHeight)
                insets
            }

            ViewCompat.setOnApplyWindowInsetsListener(view, callback)
        }

        override fun removeCallBack(view: View) {
    
    
            ViewCompat.setOnApplyWindowInsetsListener(view, null)
        }
    }

    private class Impl1 : Impl {
    
    
        override var navAndKeyBoardHeight: Int = 0

        private lateinit var callback: ViewTreeObserver.OnGlobalLayoutListener

        override fun setCallBack(view: View, listener: (keyboardHeight: Int) -> Unit) {
    
    
            val screenHeight = getRealScreenHeight(view.context)
            //当变化高度大于屏幕高度四分之一才认为是键盘弹起
            val keyboardHeightCriterion = screenHeight / 4

            callback = ViewTreeObserver.OnGlobalLayoutListener {
    
    
                val rect = Rect()
                view.getWindowVisibleDisplayFrame(rect)
                val height = screenHeight - rect.bottom
                if (height != navAndKeyBoardHeight) {
    
    
                    //设置后navAndKeyBoardHeight再回调
                    val isShow = abs(height - navAndKeyBoardHeight) > keyboardHeightCriterion
                    navAndKeyBoardHeight = height
                    if (isShow) {
    
    
                        listener.invoke(height)
                    }
                }
            }

            view.viewTreeObserver.addOnGlobalLayoutListener(callback)
        }

        override fun removeCallBack(view: View) {
    
    
            view.viewTreeObserver.removeOnGlobalLayoutListener(callback)
        }

        @Suppress("deprecation")
        fun getRealScreenHeight(context: Context): Int {
    
    
            val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager

            val display = windowManager.defaultDisplay
            return when {
    
    
                Build.VERSION.SDK_INT >= 17 -> {
    
    
                    val outPoint = Point()
                    display.getRealSize(outPoint)
                    outPoint.run {
    
    
                        x.coerceAtLeast(y)
                    }
                }
                Build.VERSION.SDK_INT >= 13 -> {
    
    
                    val outPoint = Point()
                    display.getSize(outPoint)
                    outPoint.run {
    
    
                        x.coerceAtLeast(y)
                    }
                }
                else -> {
    
    
                    display.height
                }
            }
        }
    }

    private interface Impl {
    
    
        var navAndKeyBoardHeight: Int
        fun setCallBack(view: View, listener: (navAndKeyBoardHeight: Int) -> Unit)
        fun removeCallBack(view: View)
    }

}

猜你喜欢

转载自blog.csdn.net/Reven_L/article/details/130509833