android - 怎么不使用 findViewById?
问题描述
通常我们不会在 kotlin 中使用 findViewById (R.id.listView),因为 Android Studio 会自动为我们完成(我们不需要查找视图)。但是这个例子表明我们需要它(在这行代码中):
val listView = findViewById<ListView>(R.id.listView) as ListView.
为什么我们在这个例子中使用这条线?不使用怎么办?
解决方案
如果您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
当然如果您出于某种原因想要混合使用这两种方法,它仍然可用。
推荐阅读
- json - 我可以将嵌套的 json 解组为平面结构吗
- python - 以统一的 bin 大小移动 bin 边缘 - Python
- python - 验证数据可以是 tensorflow.keras 2.0 中的生成器(而训练数据是数组)吗?
- aframe - 光标停留在 iPhone iOS safari、iOS google chrome、iOS Mozilla 上的加载位置
- python - 聚类每行字数很少的行,更喜欢 levenshtein
- kotlin - 如何在 Ktor 客户端中设置内容类型字符集(不是接受字符集)
- c# - IHostedService 无法完美运行某些代码行没有触发如何处理?
- variables - deftype 如何处理符号以及为什么它与 defvar/defun 不同
- python - 我通过升级到 TensorFlow 2.1 得到了这个错误:“AttributeError: 'Operation' object has no attribute '_graph'”
- r - 如何计算同一组中同一列中 2 个非日期值之间的差异?