Kotlin synthetic in Adapter or ViewHolder

busylee picture busylee · Oct 23, 2015 · Viewed 40.7k times · Source

I am new in kotlin. I have found and tried to use synthetic method instead of annoying method findViewById in my Activity class, but I have found "If we want to call the synthetic properties on View (useful in adapter classes), we should also import kotlinx.android.synthetic.main.view.*." But I can't figure out how it exactly works? Is there any examples?

Answer

Peter Zhao picture Peter Zhao · Oct 30, 2015

Simple example from https://github.com/antoniolg/Kotlin-for-Android-Developers

import kotlinx.android.synthetic.item_forecast.view.*

class ForecastListAdapter() : RecyclerView.Adapter<ForecastListAdapter.ViewHolder>() {

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {

        fun bindForecast(forecast: Forecast) {
            itemView.date.text = forecast.date.toDateString()
        }
    }
}

No need to write

val view = itemView.findViewById(R.id.date) as TextView
view.text = forecast.date.toDateString()

Just

itemView.date.text = forecast.date.toDateString()

Simple and effective!