android - 空对象引用上的 AlertDialog 按钮侦听器
问题描述
我想制作AlertDialog
完全自定义的布局。如果用户使用按钮,它现在应该AlertDialog
只在我调用时关闭dialog.cancel()
。
我将对话框更改为以下结构:
val builder = AlertDialog.Builder(this, R.style.AlertDialogStyle)
val inflater = this.layoutInflater
val dialogView: View = inflater.inflate(R.layout.alert_dialog_et_layout, null)
builder.apply {
setMessage(R.string.dialog_msg)
setPositiveButton(R.string.dialog_accept_label, null)
setNegativeButton(R.string.dialog_close_label, null)
setView(dialogView)
}
val alertDialog = builder.create()
val positiveBtn = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
val negativeBtn = alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE)
alertDialog.show()
positiveBtn.setOnClickListener {
//do some stuff with data
}
negativeBtn.setOnClickListener {
alertDialog.cancel()
}
但这会抛出异常:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
解决方案
Builder
已经为您提供了设置 onClickListeners 的位置。在那里做,你可以摆脱setOnClickListener
你放在底部的电话(这是那些给你带来问题的电话):
builder.apply {
builder.setMessage(R.string.dialog_msg)
builder.setPositiveButton(R.string.dialog_accept_label, positiveClickListener)
builder.setNegativeButton(R.string.dialog_close_label, negativeClickListener)
builder.setView(dialogView)
}
推荐阅读
- command - Vanilla Minecraft Commands - 我如何计算目标中的玩家数量?
- javascript - 自定义规则 ESLint 用于使用 Array.push 而不是直接赋值将项目添加到数组
- angular - 从spring boot中读取字节数组到角度并在新页面上显示内容
- pycharm - 将我的目标代码在 pycharm 上运行,'^' 不起作用
- javascript - 无法使用 csv 文件附加到 d3 js 5 中的 svg
- python - 在python中,我如何阅读需要一些时间才能加载的页面?
- apache-spark - 优化 Delta Lake 中的合并(Databricks 开源)
- java - 部署 javafx 应用程序后出错
- c++ - 如何使用 std::uniform_int_distribution
::参数()? - c++ - 如何将字符串数组传递给 main()