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

Android项目报错:空对象调用MaterialButton.setOnClickListener()

Android空指针异常解决(MaterialButton点击监听场景)

错误信息

Attempt to invoke virtual method 'void com.google.android.material.button.MaterialButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.jawaher.ff.activities.QuizActivity$4.onFinish(QuizActivity.java:377)

错误触发位置:watchAdBtn.setOnClickListener(new View.OnClickListener() {})代码行

问题场景

当userLives=0且questionAttempted<questionLimit时,创建Dialog并加载布局,尝试获取布局中的watchAdBtn并设置点击监听,但此时该按钮对象为空。

解决步骤

  • 核对布局文件中MaterialButton的id与代码中findViewById传入的id完全一致,注意大小写、下划线等细节,比如代码用R.id.watch_ad_btn,布局里不能写成watchAdBtn。
  • 确保Dialog加载布局的顺序正确:先调用dialog.setContentView(R.layout.xxx),再通过dialog.findViewById(R.id.xxx)获取按钮,不能直接用Activity的findViewById,因为Dialog有独立的视图层级。
  • 检查布局文件中的按钮控件类型,必须是com.google.android.material.button.MaterialButton,而非普通Button或其他控件,类型不匹配会导致findViewById返回null。
  • 确认Dialog对象已完成初始化,避免在调用setContentView之前就去获取控件实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 09:55:21