Is it possible to call a method inside another instance?

0

I have a Activity that shows a custom AlertDialog , as the class of Activity was kind of big I put the call of this Alert in another class in a static method. When I clicked on a certain Alert button (or when I closed it) I wanted a method of the Activity class to be executed (which is in charge of updating a ListView), but to change the ListView it would need to be called in the instance where Activity is running. Can I use this method with the context of the Activity or some other medium? I thought about making this class of AlertDialog as a partial class of Activity, but from what I saw this is not possible in Kotlin.

    
asked by anonymous 26.03.2018 / 04:41

2 answers

1

You can pass a function to be executed when the button is clicked.

In your static class:

fun buildDialog(context: Context, action: () -> Unit) {
  AlertDialog.Builder(context)
      .setTitle("Title")
      .setMessage("Message")
      .setPositiveButton("Confirm", { _, _ ->
        action()
      })
}

And in your Activity, when instanciating the dialog:

fun buildMyDialog() {

  Helper.buildDialog(this, {
    // UPDATE MY LIST
    // DO STUFF
  })

}
    
28.03.2018 / 19:25
0

Leonardo, I had a solution similar to yours in Java, when migrating to Kotlin, I migrated what I could to extensions (I created a directory with this name to put all extensions)

For alerts without having to pass the context, file extensions / Activity.kt:

    // Alertas

    var _alertDialogExtActivity: AlertDialog? = null // Para somente permitir um alerta ativo

    fun Activity.extAlerta(mensagem: String, callbackOK: (() -> Unit)? = null) {

     // Mostra alerta

    if (_alertDialogExtActivity != null) { // Existe um dialogo ativo ?
       _alertDialogExtActivity!!.cancel()
       _alertDialogExtActivity!!.hide()
    }

    this.runOnUiThread {
        val alertDialogBuilder = AlertDialog.Builder(this)

        alertDialogBuilder.setMessage(mensagem)
                .setCancelable(false)
                .setPositiveButton("OK") { _, _ ->
                    if (callbackOK != null) {
                        callbackOK()
                    }
                }
        _alertDialogExtActivity = alertDialogBuilder.create()
        _alertDialogExtActivity!!.show()
    }

}
    
02.05.2018 / 17:49