Home > other >  Create a custom dialog with callback in Kotlin
Create a custom dialog with callback in Kotlin

Time:11-04

I try to create a custom dialog and call it with a callback. Maybe it's not best practice but i dont have an idea to solve it better. This is the dialog:

private fun showDialog(header: String, message: String, callback: Callback? = null) {
    val dialog = Dialog(this)
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
    dialog.setCancelable(false)
    dialog.setContentView(R.layout.alert_layout)
    val body = dialog.findViewById(R.id.text) as TextView
    val title = dialog.findViewById(R.id.title) as TextView
    body.text = message
    title.text = header
    val yesBtn = dialog.findViewById(R.id.button) as Button
    //val noBtn = dialog.findViewById(R.id.noBtn) as TextView
    yesBtn.setOnClickListener {
        dialog.dismiss()
        if(callback != null) {
            callback // Here i want execute the callback
        }
    }
    //noBtn.setOnClickListener { dialog.dismiss() }
    dialog.show()
}

This is my callback and how i call the dialog:

val callback: Callback = object:Callback {
   fun run() {
      println("Callback executed")
   }
}
showDialog("My Title", "My Text", callback)

My opinion was to call the callback as an object like

callback.run()

My question:

Should my code working and how do i call my callback, because callback.run() seems not working.

CodePudding user response:

Instead of a Callback you can pass a Kotlin lambda function.

private fun showDialog(header: String, message: String, callback: (() -> Unit)? = null) {
    ...
    yesBtn.setOnClickListener {
        callback?.invoke() // Call that function
        dismiss()
    }
    ...
}

You can pass this lambda to showDialog by using a trailing lambda syntax.

showDialog("My Title", "My Text") {
    println("Callback executed")
}
  • Related