问题描述
定义全局android.widget
变量时,例如TextView
,最好使用lateinit
或by lazy
?起初我以为使用by lazy
是首选,因为它是不可变的,但我不确定.
When defining a global android.widget
variable, e.g. TextView
, is it preferable to use lateinit
or by lazy
? I initially thought using by lazy
would be preferred as its immutable but I'm not entirely sure.
by lazy
示例:
class MainActivity: AppCompatActivity() {
val helloWorldTextView by lazy { findViewById(R.id.helloWorldTextView) as TextView }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
updateTextView(helloWorldTextView)
}
fun updateTextView(tv: TextView?) {
tv?.setText("Hello?")
}
}
lateinit
示例:
class MainActivity: AppCompatActivity() {
lateinit var helloWorldTextView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
helloWorldTextView = findViewById(R.id.helloWorldTextView) as TextView
updateTextView(helloWorldTextView)
}
fun updateTextView(tv: TextView?) {
tv?.setText("Hello?")
}
}
在定义全局android.widget
var/val时使用一个使用另一个是否有好处?使用by lazy
定义android.widget
val是否有任何陷阱?决定只是基于您想要可变还是不变的值?
Are there any benefits of using one over the other when defining a global android.widget
var/val? Are there any pitfalls with using by lazy
to define a android.widget
val? Is the decision just based on whether you want a mutable or immutable value?
推荐答案
by lazy
有一个陷阱. widget属性将是只读的,因此是技术上的最终版本(用Java术语).但是,没有记录保证onCreate()
对于一个实例仅被调用一次.同样,findViewById()
可能返回null
.
There's one pitfall with by lazy
. The widget property would be read-only and therefore technically final (in Java terms). But there's no documented guarantee that onCreate()
is called only once for an instance. Also findViewById()
could return null
.
因此,最好使用lateinit
,并且会告诉您是否在onCreate()
之前使用了val
.
So using lateinit
is preferable and you'll get an exception to tell you if the val
was used before onCreate()
.
第三种可能性是 Android综合属性.然后,您完全不必担心变量.
A third possibility would be Android synthetic properties. Then you don't need to worry about the variables at all.
import kotlinx.android.synthetic.main.activity_main.*
helloWorldTextView.text = "Hello?"
这篇关于"lateinit"或“偷懒"定义全局android.widget var/val时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!