Kotlin synthetic in Adapter or ViewHolder

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!


You need

import kotlinx.android.synthetic.row_wall.view.*

And later something along the lines of:

convertView.titleText.text = item.title

The point is that the view.* introduces extensions to the View class.


Kotling 1.1.4 out

Further information : https://antonioleiva.com/kotlin-android-extensions/

You need to enable Kotlin Android Extentions by adding this to your build.gradle:

apply plugin: 'org.jetbrains.kotlin.android.extensions'
androidExtensions {
    experimental = true
}

Since this new version of Kotlin, the Android Extensions have incorporated some new interesting features: caches in any class (which interestingly includes ViewHolder)

Using it on a ViewHolder (or any custom class). Note that this class should implement LayoutContainer interface:

class ViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), 
        LayoutContainer {

    fun bind(title: String) {
        itemTitle.text = "Hello Kotlin!"
    }
}