Android Kotlin - How to pass a named function to DialogInterface.OnClickListener parameter in another function?

Viewed 2364

This is my function declaration,

fun MyDialog(ctx: Context, msg: String, yestext: String = "", OnYes: DialogInterface.OnClickListener? = null): AlertDialog

fun MyClickListener(){}

How do i pass MyClickListener into MyDialog?

MyDialog(context, "Delete data", "Yes", MyClickListener) showed type mismatch.

In DialogInterface.class

  public interface OnClickListener {
    void onClick(DialogInterface var1, int var2);
  }
1 Answers

You need an implementation of the DialogInterface.OnClickListener in order to pass it to it.

Like:

class MyClickListener : DialogInterface.OnClickListener {
    override fun onClick(var1: DialogInterface, var2: Int) {/* Code */}
}

// then call the constructor.
MyDialog(ctx, "", "", MyClickListener())

But indeed this isn't the cleanest way further. Just like java you can do SAM conversions in Kotlin 1.4.

// inline implementation of DialogInterface.OnClickListener using SAM conversion
MyDialog(ctx, "", "") {/* Code */}

And if you want to, you can extract the SAM conversion into a function that suits your usecase.

fun MyClickListener() =
    DialogInterface.OnClickListener { /* Code */ }

//Now call like this
MyDialog(ctx, "", "", MyClickListener())
Related