Android 如何不使用findViewById?

Android 如何不使用findViewById?,android,kotlin,Android,Kotlin,通常我们不会在kotlin中使用findViewById(R.id.listView),因为Android studio会自动为我们使用它(我们不需要查找视图)。 但示例表明,我们需要为您提供它(在这行代码中): val listView=findviewbyd(R.id.listView)作为listView。 为什么我们在这个例子中使用这一行?如何不使用它?通常,当您需要布局文件中的视图时,可以导入以下内容: kotlinx.android.synthetic.main.<layou

通常我们不会在kotlin中使用findViewById(R.id.listView),因为Android studio会自动为我们使用它(我们不需要查找视图)。 但示例表明,我们需要为您提供它(在这行代码中):

val listView=findviewbyd(R.id.listView)作为listView。

为什么我们在这个例子中使用这一行?如何不使用它?

通常,当您需要布局文件中的视图时,可以导入以下内容:

kotlinx.android.synthetic.main.<layout filename>.<id of view>
kotlinx.android.synthetic.main。。
如果需要布局文件中的所有视图,可以使用:

kotlinx.android.synthetic.main.<layout filename>.*
kotlinx.android.synthetic.main*
如果您使用的是来自Kotlin的,那么您永远不需要强制转换(来自API级别26及以上)。您应该使用以下两种方法之一:

val myTV1 = findViewById<TextView>(R.id.myTextView)
val myTV2: TextView = findViewById(R.id.myTextView)
这是获取视图引用并按原样在Kotlin中使用它们的一种非常有效的方法


但是,如果您也在项目中启用了(通过模块级
build.gradle
文件中的
apply插件:“kotlin android extensions”
行),您也可以通过其提供的合成属性通过其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
当然,如果出于任何原因您想混合使用这两种方法,它仍然可用。

如果您使用的是kotlin合成库,则不需要使用findViewById,否则您需要调用findViewById来获取任何视图的引用。
myTV1.text = "testing"
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"
    }

}