美文网首页
Android获取软键盘高度

Android获取软键盘高度

作者: _发强 | 来源:发表于2023-04-25 15:43 被阅读0次
        private var keyboardHeight = 0
    
        private fun observeKeyboardHeight() {
            val rootView: View = window.decorView.findViewById(android.R.id.content)
            rootView.viewTreeObserver.addOnGlobalLayoutListener(object :
                ViewTreeObserver.OnGlobalLayoutListener {
    
                private var isKeyboardVisible = false
    
                override fun onGlobalLayout() {
                    val rect = Rect()
                    rootView.getWindowVisibleDisplayFrame(rect)
                    val screenHeight = rootView.rootView.height
                    keyboardHeight = screenHeight - rect.bottom
    
                    if (keyboardHeight > 150 && !isKeyboardVisible) {
                        isKeyboardVisible = true;
                        // 键盘弹出
                        Log.i("show....$keyboardHeight")
                        showedKeyboard(true)
                    } else if (keyboardHeight <= 150 && isKeyboardVisible) {
                        isKeyboardVisible = false;
                        // 键盘隐藏
                        Log.i("hide....$keyboardHeight")
                        showedKeyboard(false)
                    }
                }
            })
        }
    

    某些设备需要同步配合获取底部导航栏高度:

        private fun getNavigationBarHeight(context: Context): Int {
            try {
                val resourceId =
                    context.resources.getIdentifier("navigation_bar_height", "dimen", "android")
                return if (resourceId > 0) {
                    context.resources.getDimensionPixelSize(resourceId)
                } else {
                    0
                }
            } catch (e: Exception) {
                return 0
            }
        }
    

    相关文章

      网友评论

          本文标题:Android获取软键盘高度

          本文链接:https://www.haomeiwen.com/subject/jxcmjdtx.html