Is it possible to call a method within another instance?

Asked

Viewed 219 times

0

I have a Activity which shows a AlertDialog customized, as the class of Activity I put the call of this Alert in another class in a static method. When clicking a certain Alert button (or when closing it) I wanted a method of the Activity class to be executed (which takes care of updating a Listview), but to change the Listview it would need to be called in the instance where the Activity is running. With the context of Activity or any other means is it possible to use that method? I thought of making this Alertdialog class as a partial class from Activity, but from what I’ve seen it’s not possible in Kotlin.

2 answers

1


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

In its static method class:

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

And in your Activity, when instantiating the dialog:

fun buildMyDialog() {

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

}

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 the extensions)

For alerts without passing 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()
    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.