Home > database >  How to make button available directly from function
How to make button available directly from function

Time:09-30

Hi i am making an app that follows the MVVM structure i took a look at this tutorial https://www.youtube.com/watch?v=d7UxPYxgBoA&t=152s in this tutorial the person that teaches use code that looks like this...

private fun initializeUi() {
    val factory = InjectorUtils.provideQuotesViewModelFactory()
    val viewModel = ViewModelProviders.of(this, factory)
            .get(QuotesViewModel::class.java)

    viewModel.getQuotes().observe(this, Observer { quotes ->
        val stringBuilder = StringBuilder()
        quotes.forEach{ quote ->
            stringBuilder.append("$quote\n\n")
        }
        textView_quotes.text = stringBuilder.toString()
    })

    button_add_quote.setOnClickListener {
        val quote = Quote(editText_quote.text.toString(), editText_author.text.toString())
        viewModel.addQuote(quote)
        editText_quote.setText("")
        editText_author.setText("")
    }
}

as you can see he doesnt initialize a variable to find the button. how is this possible... i tried to do this in a fragment and it does not work? tell me if you need further code and ill add it in.

CodePudding user response:

It's using Kotlin synthetics, which is a way to bind the layout xml to the activity or fragment class. You can see it in the source code for the project on GitHub:

https://github.com/ResoCoder/mvvm-android-architecture-crash-course/blob/master/app/src/main/java/com/resocoder/mvvmbasicstut/ui/quotes/QuotesActivity.kt#L10

import kotlinx.android.synthetic.main.activity_quotes.*

However, Kotlin synthetics has been deprecated and you should be using view binding instead. More info here:

https://developer.android.com/topic/libraries/view-binding/migration

  • Related