【发布时间】:2019-10-11 09:06:34
【问题描述】:
我正在制作一个小型测验游戏,我不想为每个 Activity 中的按钮制作每个功能,因为不要重复自己。但是当我启动我的应用程序时,它会因空指针异常而崩溃。
我在底部尝试了解决方案,并在 ButtonManager 类中创建了一个函数,其中我有一个 String 作为构造函数参数,并将其转换为上面命名的函数。
这就是我的 ButtonManager 类的样子:
class ButtonManager(buttonName: Int) : AppCompatActivity() {
val button: Button = findViewById(buttonName)
fun quitGame(){
finish()
}
}
这是我的函数调用在我的 Activity 中的样子:
ButtonManager(R.id.quitGameButton).button.setOnClickListener {
ButtonManager(R.id.quitGameButton).quitGame()
}
这是错误代码:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
【问题讨论】:
-
你调用 setcontentview 吗?
-
不,我不叫它任何地方
-
如果没有可见的布局,那么你不能使用“findviewbyId”,因为还没有视图。
-
ButtonManager(findViewById(R.id.buttonid))
标签: android kotlin nullpointerexception