如何懒惰地初始化UI组件



给定以下示例,如何使文本视图的懒惰初始化?我试图通过 lateinit 进行初始化,但它无法通过懒惰的lambda函数

进行。

活动

    var mTextViewResult : TextView by lazy { findViewById(R.id.tvResult) }
    onCreate(...) {...}

而不是使用var,您应该使用val

val mTextViewResult : TextView by lazy { findViewById(R.id.tvResult) }

弃用此外,如果应用Kotlin Android扩展插件,则不必致电findViewById()

在应用程序级别build.gradle添加kotlin android扩展的插件

apply plugin: "com.android.application"
apply plugin: "kotlin-android"
apply plugin: "kotlin-kapt"
apply plugin: "kotlin-android-extensions" // this plugin
...

现在您可以通过导入布局参考来使用tvResult

import kotlinx.android.synthetic.main.<layout>.*
class MainActivity : AppCompatActivity{
...
}

我建议您使用数据列表库来更轻松地初始化/使用布局项目。

做以下操作:

class YourClassActivity() {
    private var myTextView : TextView? = null    // At first, myTextView is null. Do not use it !
    private var viewModel = YourViewModel()
    override fun onCreate(...) {
        val binding = DataBindingUtil.setContentView<ActivityYourClassBinding>(this, R.layout.activity_your_class) // DataBinding will set your view
        binding.viewModel = yourViewModel
        // Init layout variables
        myTextView = binding.myTextView // If your TextView id is "my_text_view"
        /*
        ** Now you can use 'myTextView' in any of your function (not just onCreate).
        ** Just do not forget to put the nullable '?' mark after its name.
        */
        myTextView?.text = "Hello World"
        myTextView?.setOnClickListener { clear() }
    }
    private fun clear() {
        myTextView?.text = "" // You can use your variable anywhere you want !
    }
}

您不能将lazyvar一起使用。您可以在OnCreate 中使用var lateinit mTextViewResult : TextView和MtextViewResult = FindViewById(...(,也可以使用Synthetics访问XML中定义的ID的Synthetics。

最新更新