Search code examples
androidkotlinlazy-initialization

how to initialize a UI-component lazily


Given the below example, how can I make lazy initialization of the TextView? I attempted to do the initialization via lateinit and it worked, but it cant be done via lazy lambda function

Activity

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

    onCreate(...) {...}

Solution

  • Instead of using var you should use val

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

    DEPRECATED Furthermore, if kotlin android extensions plugin is applied you do not have to call findViewById() too.

    In application level build.gradle add plugin for kotlin android extension

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

    Now you can use tvResult by importing your layout reference.

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