我想用完全自定义的布局制作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
答案 0 :(得分:0)
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)
}