如何使用 Google 代码风格在 Android (Kotlin) 中声明变量?
How to declare variables in Android (Kotlin) using Google code style?
我开始在 Kotlin 中构建应用程序,我想知道如何正确初始化变量。例如在 Java 中是这样的:
private TextView mSomeTextView;
然后我们在一些方法中调用findViewById。但是在 Kotlin 中我不能只写那样的东西,我需要:
private val textView: TextView = findViewById(R.id.text)
我和以前一样写在onCreate下。问题:它的位置合适吗?如果没有 - 我应该在哪里以及如何做?
你应该使用 lateinit
:
private lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
...
textView = findViewById(R.id.text)
}
我开始在 Kotlin 中构建应用程序,我想知道如何正确初始化变量。例如在 Java 中是这样的:
private TextView mSomeTextView;
然后我们在一些方法中调用findViewById。但是在 Kotlin 中我不能只写那样的东西,我需要:
private val textView: TextView = findViewById(R.id.text)
我和以前一样写在onCreate下。问题:它的位置合适吗?如果没有 - 我应该在哪里以及如何做?
你应该使用 lateinit
:
private lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
...
textView = findViewById(R.id.text)
}