首页 > 解决方案 > 怎么不使用 findViewById?

问题描述

通常我们不会在 kotlin 中使用 findViewById (R.id.listView),因为 Android Studio 会自动为我们完成(我们不需要查找视图)。但是这个例子表明我们需要它(在这行代码中):

val listView = findViewById<ListView>(R.id.listView) as ListView.

为什么我们在这个例子中使用这条线?不使用怎么办?

标签: androidkotlin

解决方案


如果您findViewById从 Kotlin 使用,则永远不需要强制转换(从 API 级别 26 及更高级别)。您应该使用以下两种方式之一:

val myTV1 = findViewById<TextView>(R.id.myTextView)
val myTV2: TextView = findViewById(R.id.myTextView)

然后你可以通过这些变量访问它的属性:

myTV1.text = "testing"

这是获取 View 引用并在 Kotlin 中按原样使用它们的一种完全有效的方式。


但是,如果您还在项目中启用了Kotlin Android 扩展apply plugin: 'kotlin-android-extensions'(通过模块级build.gradle文件中的行),您还可以通过其提供的合成属性通过其 ID 引用您的视图,只需确保您有正确的导入,例如:

import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        myTextView.text = "testing"
    }

}

请注意,Kotlin Android Extensions 完全是可选的,如果您确实使用它,findViewById当然如果您出于某种原因想要混合使用这两种方法,它仍然可用。


推荐阅读