美文网首页
监听软键盘滚动ScrollView

监听软键盘滚动ScrollView

作者: 河马过河 | 来源:发表于2025-11-17 10:52 被阅读0次
  /**
     * 设置键盘状态监听
     */
    private fun setupKeyboardListener() {
        keyboardLayoutListener = KeyboardUtil.observeSoftKeyboard(binding.root) { _, visible ->
            if (visible) {
                // 键盘弹出:保存当前滚动位置,显示占位View,滚动到底部
                originalScrollPosition = binding.nsvTemplateGenerateVideo.scrollY
                binding.vKeyboardSpacer.visibility = View.VISIBLE
                
                binding.nsvTemplateGenerateVideo.postDelayed({
                    binding.nsvTemplateGenerateVideo.fullScroll(View.FOCUS_DOWN)
                }, 100)
            } else {
                // 键盘隐藏:隐藏占位View,恢复滚动位置
                binding.vKeyboardSpacer.visibility = View.GONE
                
                binding.nsvTemplateGenerateVideo.postDelayed({
                    binding.nsvTemplateGenerateVideo.smoothScrollTo(0, originalScrollPosition)
                }, 100)
            }
        }
    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        if (loadingDialog != null && loadingDialog?.isShowing == true) {
            loadingDialog?.dismiss()
        }
        KeyboardUtil.removeSoftKeyboardObserver(binding.root, keyboardLayoutListener)
    }

       <!-- 键盘占位View -->
            <View
                android:id="@+id/vKeyboardSpacer"
                android:layout_width="match_parent"
                android:layout_height="@dimen/dp_200"
                app:layout_constraintTop_toBottomOf="@id/clTemplateGenerateVideoPromptRatio"
                android:visibility="gone" />
                
        </androidx.constraintlayout.widget.ConstraintLayout>
    </androidx.core.widget.NestedScrollView>

相关文章

网友评论

      本文标题:监听软键盘滚动ScrollView

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