You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Window#setDecorFitsSystemWindows替代已弃用的SOFT_INPUT_ADJUST_RESIZE?

解决BottomSheetDialogFragment被键盘遮挡问题(替代弃用的SOFT_INPUT_ADJUST_RESIZE)

原来使用的WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE已被官方弃用,推荐通过Window#setDecorFitsSystemWindows(boolean)实现窗口适配软键盘的效果,针对BottomSheetDialogFragment的修改方式如下:

修改后的完整代码

import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.yocto.wetodo.databinding.TodoInputDialogFragmentBinding

class TodoInputDialogFragment : BottomSheetDialogFragment() {

    private var _binding: TodoInputDialogFragmentBinding? = null
    // 仅在onCreateView至onDestroyView期间有效
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = TodoInputDialogFragmentBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState)
        
        dialog.window?.apply {
            // 核心设置:禁用系统对DecorView的自动调整,让BottomSheet响应软键盘弹出而偏移
            setDecorFitsSystemWindows(false)
        }

        return dialog
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

关键说明

  • setDecorFitsSystemWindows(false):关闭系统对窗口根布局的自动适配逻辑,使BottomSheet能够感知软键盘的弹出事件,自动向上调整位置避免被遮挡。
  • 无需保留弃用的SOFT_INPUT_ADJUST_RESIZE配置,setDecorFitsSystemWindows(false)已覆盖该功能的核心逻辑。
  • 建议确保BottomSheet内部布局包含可滚动容器(如ScrollView、RecyclerView),这样软键盘弹出时,超出屏幕的内容仍可正常滚动查看。

内容的提问来源于stack exchange,提问作者Cheok Yan Cheng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 10:02:11