0

我正在尝试使用 Kotlin 和 Anko 的 DSL 创建一个警报对话框,让用户选择图像,然后将其加载到 ImageView 中。现在我只是想让 ImageView 工作,所以我单击按钮以使用 Picasso 从 URL 加载预选的图像。

当我单击警报对话框中的按钮时,我收到此错误:

kotlin.TypeCastException: null 不能转换为非 null 类型 android.widget.ImageView

我猜出于某种原因没有通过 findViewById 加载 ImageView。有谁知道这可能是为什么?我猜 Anko 的 DSL 有一些我不知道的奇怪行为。

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()
4

1 回答 1

2

您可以获得对ImageView此类的参考,并避免完全处理 ID:

val iv = imageView()
...
    onClick {
        Picasso.with(this@MainActivity)
                .load("http://SomeUrl/image.jpg")
                .into(iv)
    }
...
于 2017-06-09T16:46:15.917 回答