Search code examples
kotlinandroid-cameraandroid-alertdialogandroid-storage

How to use OnClickListener for items in AlertDialog Kotlin?


So i get this java code about AlertDialog:

AlertDialog.Builder builder= new AlertDialog.Builder(context:this);
builder.setTitle("Pick Image")
     .setItems(options, new DialogInterface.OnClickListener(){
          @Override
          public void onClick(DialogInterface dialog, int which){
            if(which==0){
             if(checkCameraPermission())pickFromcamera();
             else requestCameraPermission(); 
            } else{
              if(checkStoragePermission()) pickFromGallery();
              else requestStoragePermission();
             }
    }
}

And i try to use this in my Kotlin project, so i change it a bit. My code look like:

val options: Array<String> = arrayOf("Kamera","Gallery")
        val builder= AlertDialog.Builder(this)
        builder.setTitle("Pilih Gambar")
            .setItems(options,DialogInterface.OnClickListener(){
                @Override
                fun onClick(dialog: DialogInterface, which: Int){
                    if(which==0){
                        if(checkCameraPermission()){
                            pickFromCamera()
                        }
                        else{
                            requestCameraPermission()
                        }
                    }
                    else{
                        if(checkStoragePermission()){
                            pickFromGallery()
                        }
                        else{
                            requestStoragePermission()
                        }
                    }
                }
            })
            .show()

But i get this error : Expected 2 parameters of types DialogInterface!, Int at my setItems. Why is this happen? What did i do wrong?


Solution

  • You combined Java with Kotlin. Try writing it like this with your logic inside of the lambda assuming you're trying to do it in Kotlin.

        val options: Array<String> = arrayOf("Kamera","Gallery")
            val builder= AlertDialog.Builder(requireContext())
            builder.setTitle("Pilih Gambar").setItems(options) { dialog, which ->
                if(which==0){
                        if(checkCameraPermission()){
                            pickFromCamera()
                        }
                        else{
                            requestCameraPermission()
                        }
                    }
                    else{
                        if(checkStoragePermission()){
                            pickFromGallery()
                        }
                        else{
                            requestStoragePermission()
                        }
                    }
            }
            .show()