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

App崩溃闪退求助:我的Fragment代码运行报错该如何修复?

故障定位与修复方案

崩溃原因

崩溃由**空指针异常(NullPointerException)**触发:你直接调用start2BT.setOnClickListener(),但start2BT变量未初始化,未关联布局文件中的按钮实例,此时它的值为null,调用null对象的方法会导致应用崩溃。

修复方法

方法1:使用findViewById初始化控件

修改onViewCreated方法,先通过view.findViewById获取按钮实例:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    val start2BT = view.findViewById<Button>(R.id.start2BT)
    start2BT.setOnClickListener {
        Navigation.findNavController(it).navigate(Start1FragmentDirections.actionStart1ToStart2())
    }
}

方法2:使用View Binding(推荐,更安全)

视图绑定会自动生成绑定类,避免手动findViewById的空指针风险:

  1. 在模块级build.gradle中启用视图绑定:
android {
    ...
    buildFeatures {
        viewBinding true
    }
}
  1. 修改Fragment代码:
private var _binding: FragmentStart1Binding? = null
private val binding get() = _binding!!

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

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    binding.start2BT.setOnClickListener {
        Navigation.findNavController(it).navigate(Start1FragmentDirections.actionStart1ToStart2())
    }
}

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 05:35:19