Amrmsmb
Amrmsmb

Reputation: 11406

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(...) {...}

Upvotes: 3

Views: 2505

Answers (3)

Sagar Chapagain
Sagar Chapagain

Reputation: 1763

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{
...
}

Upvotes: 3

Thracian
Thracian

Reputation: 67189

You can't use lazy with var. You can use var lateinit mTextViewResult : TextView and mTextViewResult = findViewById(...) in onCreate or you can use synthetics to access TextView by it's id defined in xml.

Upvotes: 0

Mathieu
Mathieu

Reputation: 1713

I suggest you to use DataBinding library to get easier initialization / use of your layout items.

Do as follow :

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 !
    }
}

Upvotes: 0

Related Questions