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

Android Studio(Kotlin)中ViewBinding与setOnApplyWindowInsetsListener冲突致崩溃

问题分析与解决方案

崩溃原因

你当前的代码顺序错误:在加载并设置布局之前就调用了findViewById(R.id.main)。此时Activity还未关联布局文件,findViewById返回null,后续调用setOnApplyWindowInsetsListener就会触发NullPointerException,也就是LogCat里提示的"Attempt to invoke virtual method on a null object reference"。

修正后的代码

调整代码顺序,先初始化ViewBinding并设置布局,再通过Binding对象获取目标View设置监听:

// 先初始化ViewBinding并设置布局
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)

// 直接通过binding获取目标View,无需findViewById
ViewCompat.setOnApplyWindowInsetsListener(binding.main) { v, insets ->
    val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
    v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
    insets
}

为什么这样有效

ViewBinding会根据你的布局文件自动生成对应的Binding类,其中包含了布局中所有带id的View的直接引用。当你调用setContentView(binding.root)后,布局已经成功加载到Activity中,binding.main就能安全获取到目标View,不会出现空指针问题。

内容的提问来源于stack exchange,提问作者Weird_dog

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 20:00:06