0

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()
Parker
  • 8,539
  • 10
  • 69
  • 98

1 Answers1

2

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)
    }
...
zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • Hey, that works, thanks! The only problem is if I want to access the imageView later (outside of the onClick), I still don't know how to – Parker Jun 09 '17 at 16:58
  • 2
    You can create a property inside the `Activity` and assign the `ImageView` to that too. – zsmb13 Jun 09 '17 at 16:59