Search code examples
androidkotlinanko

Dismissing Anko Dialog in onClickListener


I would like to dismiss Anko Dialog when pressing the button defined in my customLayout

val dialog = alert {
   val view = layoutInflater.inflate(R.layout.match_stats, null)
   val closeButton = view.findViewById<ImageButton>(R.id.closeButton)
   closeButton.setOnClickListener { _ -> dialog.dismiss()}
   customView = view
}
dialog.show()

I tried above code, unfortunately, I can’t get a reference to dialog in my onClickListener. Do you have any idea how to solve it?


Solution

  • You could declare variable before and assign null:

    var dialog: DialogInterface? = null
    dialog = alert {
       val view = layoutInflater.inflate(R.layout.match_stats, null)
       val closeButton = view.findViewById<ImageButton>(R.id.closeButton)
       closeButton.setOnClickListener { _ -> dialog?.dismiss()}
       customView = view
    }.show()
    

    Of course now your dialog variable is muttable and optional.