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

我想在Kotlin下面这行代码的等效代码:

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

任何帮助?

很简单,只要做下面的行动

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

也用这个标记!! kotlin将被检查为空状态

最后看下面的例子

 val btn = view!!.findViewById 

你为什么不简单地使用Kotlin Android绑定? 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 

请参阅这里

您可以使用:

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

但是,您可以使用Kotlin Android扩展插件。

只需添加到您的build.gradle

 apply plugin: 'kotlin-android-extensions' 

然后你可以避免使用findViewById方法,例如:

 textView.text = "My text" 

您可以访问该视图,而无需使用第三方库,只需使用xml文件中分配的id

在片段中初始化视图:

 val manageAddress=view.findViewById(R.id.textView) 

而已