简体   繁体   English

无法为Kotlin / Anko DSL定义的ImageView设置图像

[英]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. 我正在尝试使用Kotlin和Anko的DSL创建警报对话框,允许用户选择图像,然后将其加载到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. 现在,我只是想使ImageView正常工作,所以我单击了按钮,以使用Picasso从URL加载预选的图像。

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 kotlin.TypeCastException:无法将null强制转换为非null类型android.widget.ImageView

I'm guessing for some reason the ImageView isn't being loaded through findViewById. 我猜测由于某种原因未通过findViewById加载ImageView。 Does anyone know why this might be? 有谁知道为什么会这样吗? I'm guessing Anko's DSL has some weird behavior I don't know about. 我猜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()

You can get a reference to the ImageView like this and avoid having to deal with IDs altogether: 您可以像这样获取对ImageView的引用,而不必完全处理ID:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM