"lateinit" or "by lazy" when defining global android.widget var/val

"lateinit" or "by lazy" when defining global android.widget var/val

定义全局 android.widget 变量时,例如TextView,用lateinit好还是by lazy好?我最初认为使用 by lazy 是首选,因为它是不可变的,但我不完全确定。

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 有什么陷阱吗?该决定是否仅基于您想要可变值还是不可变值?

by lazy 有一个陷阱。小部件 属性 将是只读的,因此 技术上 最终(在 Java 术语中)。但是没有书面保证 onCreate() 只为一个实例调用一次。 findViewById() 也可以 return null.

所以使用 lateinit 更可取,如果 valonCreate().

之前使用,您将得到一个例外告诉您

第三种可能性是Android synthetic properties。那么你根本不需要担心变量。

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

helloWorldTextView.text = "Hello?"