Search code examples
androidkotlinpicassoanko

Trouble setting an image for a Kotlin/Anko DSL defined ImageView


I'm trying to use Kotlin and Anko's DSL to create an alert dialog that lets a user pick an image, and then loads it into an ImageView. Right now I'm just trying go get the ImageView to work, so I have the button click to load a preselected image from a URL using Picasso.

When I click the button in the alert dialog, I get this error:

kotlin.TypeCastException: null cannot be cast to non-null type android.widget.ImageView

I'm guessing for some reason the ImageView isn't being loaded through findViewById. Does anyone know why this might be? I'm guessing Anko's DSL has some weird behavior I don't know about.

fab.setOnClickListener { view ->
            alert {
                title = "New Post"
                customView {
                    verticalLayout {

                        val subject = editText {
                            hint = "Subject"
                        }
                        imageView {
                            id = R.id.picked_image
                        }
                        linearLayout {
                            gravity = Gravity.CENTER
                            button("Choose Photo") {
                                onClick {
                                    Picasso.with(this@MainActivity)
                                            .load("http://SomeUrl/image.jpg")
                                            .into(findViewById(R.id.picked_image) as ImageView)

                                }
                            }
                            button("Choose Image") {}
                        }


                        positiveButton("Post") {  }
                        negativeButton("Cancel") {}
                    }
                }
            }.show()

Solution

  • You can get a reference to the ImageView like this and avoid having to deal with IDs altogether:

    val iv = imageView()
    ...
        onClick {
            Picasso.with(this@MainActivity)
                    .load("http://SomeUrl/image.jpg")
                    .into(iv)
        }
    ...