首页 > 解决方案 > 空对象引用上的 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

标签: androidkotlinandroid-dialog

解决方案


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)
}

推荐阅读