监听软键盘滚动ScrollView
2025-11-17 本文已影响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>