0

I want to make AlertDialog with completely custom layout. If user use button it should now close AlertDialog only if I call dialog.cancel().

I changed my dialog to this structure:

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

But this will throw exception:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
martin1337
  • 2,384
  • 6
  • 38
  • 85

1 Answers1

0

The Builder already gives you a place to set onClickListeners. Do it there and you can get rid of the setOnClickListener calls you placed at the bottom (which are the ones causing you problems):

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)
}
Gavin Wright
  • 3,124
  • 3
  • 14
  • 35
  • Does not work when trying to explicitly do it this way and not the standard way. See https://stackoverflow.com/a/27345656/7061105 – Akito Nov 12 '21 at 12:35