如何在 kotlin 中初始化片段 class 中的视图?

How to initialise view in fragment class in kotlin?

我想要 Kotlin 中以下行的等效代码:

TextView tv = view.findViewbyId(R.id.textView);

有什么帮助吗?

为什么不直接使用 Kotlin Android Binding?这是 Kotlin 的扩展,有助于绑定视图,无需任何 "bindView" 或 findViewById 代码来干扰业务逻辑。

一旦你深入研究,你肯定会发现它很棒,而且以后写的代码更少。

值得一看。 https://kotlinlang.org/docs/tutorials/android-plugin.html


但你仍然可以使用原来的 kotlin

val lblLabel = findViewById(R.id.text) as TextView
 val tv: TextView = findViewById(R.id.textView) as TextView

如果你想全局声明textview,使用lateinit var tv: TextView

你可以在 kotlin 中这样做

val lv = findViewById(R.id.textView) as TextView

Kotlin 初始化:

val tv = findViewbyId(R.id.textView) as TextView

参考here

您可以使用:

val myLabel = findViewById(R.id.text) as TextView

但是您可以使用 Kotlin Android Extensions 插件。

只需添加到您的 build.gradle

apply plugin: 'kotlin-android-extensions'

那么你可以避免使用 findViewById 方法,例如:

textView.text = "My text"

您无需查找或使用第三方即可访问该视图 派对库仅使用 xml 文件中分配的 id

片段中视图的初始化:

val manageAddress=view.findViewById<TextView>(R.id.textView)

就是这样

很简单,做下面的动作就可以了

val valueName = view!!.findViewById<ObjectName>(R.id.ObjectId)

还有这个标记!! kotlin 将被检查为空状态

终于看到下面的例子了

val btn = view!!.findViewById<Button>(R.id.btn)

如果您使用 Kotlin Android 扩展(apply plugin: 'kotlin-android-extensions',请参阅 https://antonioleiva.com/kotlin-android-extensions/),您可以编写 textView 并且 IDE 将提供其多种变体在不同的布局中查看。选择合适的后,你可以这样写:

textView.text = "This is a text"

在导入中,您会看到类似 import kotlinx.android.synthetic.main.fragment_dialog.*

的内容