gpt4 book ai didi

android - 如何在布局代码中轻松访问 anko 组件

转载 作者:行者123 更新时间:2023-11-29 01:03:19 26 4
gpt4 key购买 nike

使用 Anko,可以很容易地访问之前定义的组件。例如:

verticalLayout {
val name = editText()
button("Say Hello") {
onClick { ctx.toast("Hello, ${name.text}!") }
}
}

由于编辑文本是在按钮之前定义的,因此访问起来很容易。但是,当您要访问的组件定义在当前元素之后,是当前元素的父元素,或者在当前元素的兄弟元素中时,我不知道访问它的简单方法。以下是一些示例:

之后定义的元素

verticalLayout {
button("Say Hello") {
// how to access "name" here?
}
val name = editText()
}

在同胞中定义的元素

verticalLayout {
verticalLayout {
val name = editText()
}
button("Say Hello") {
// how to access "name" here?
}
}

元素是父元素

val layout = verticalLayout {
button("Say Hello") {
// how to access "layout" here?
}
}

如果我在没有 Anko 的情况下使用传统的 XML 布局文件来做同样的事情,我可以简单地使用 findViewById() 来引用那些元素。有没有一种使用 Anko 访问它们的简单方法?

最佳答案

Since Kotlin 1.2 , 你可以使用 lateinit对于局部变量,它可能是您在这里需要的解决方案,以使您的变量达到所需的范围:

之后定义的元素:

verticalLayout {
lateinit var name: EditText
button("Say Hello") {
// use name
}
name = editText()
}

在同胞中定义的元素:

verticalLayout {
lateinit var name: EditText
verticalLayout {
name = editText()
}
button("Say Hello") {
// use name
}
}

元素是父元素:

lateinit var layout: LinearLayout
layout = verticalLayout {
button("Say Hello") {
// use layout
}
}

关于android - 如何在布局代码中轻松访问 anko 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49384535/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com