如何在Anko DSL中引用其他视图?

Mar*_*vin 15 android kotlin anko

我在我的Android项目中使用Anko,但我不知道它如何引用我在DSL中创建的子视图,当引用的视图不在我引用它的同一级别时.

以下代码有效:

alert {
    customView {
        val input = textInputLayout {
            editText {
                hint = "Name"
                textColor =resources.getColor(R.color.highlight)
            }
        }


        positiveButton("OK") { "${input.editText.text}" }
    }
}.show()
Run Code Online (Sandbox Code Playgroud)

但以下代码不起作用:

alert {
    customView {
        val vertical = verticalLayout {
            textView {
                text = "Edit device name"
                textColor = resources.getColor(R.color.highlight)
                textSize = 24F
            }
            val input = textInputLayout {
                editText {
                    hint = "Name"
                    textColor = resources.getColor(R.color.highlight)
                }
            }
        }

        positiveButton("OK") { "${vertical.input.editText.text}" }  // Cannot resolve "input"
    }
}.show()
Run Code Online (Sandbox Code Playgroud)

Kir*_*man 6

我认为有两种方法.超级hacky方式是在textInputLayout块内声明正面按钮.这是可能的,因为您可以从任何嵌套范围内访问所有外部作用域,并且该positiveButton方法在alert作用域中声明:

alert {
    customView {
        verticalLayout {
            textInputLayout {
                val editText = editText {
                    hint = "Name"
                }

                positiveButton("OK") { toast("${editText.text}") }
            }
        }
    }
}.show()
Run Code Online (Sandbox Code Playgroud)

声明可以从两个作用域访问的变量的方法就越少.但是,您需要使其可以为空,因为您无法立即初始化它:

alert {
    var editText: EditText? = null

    customView {
        verticalLayout {
            textInputLayout {
                editText = editText {
                    hint = "Name"
                }
            }
        }
    }

    positiveButton("OK") { toast("${editText!!.text}") } 
}.show()
Run Code Online (Sandbox Code Playgroud)

  • 你在谈论属性或局部变量吗?因为变量不能具有`lateinit`修饰符. (2认同)