Kotlin Android Extentions ViewBinding for RecyclerView ViewHolder (LayoutContainer)

July 24, 2018

Kotlin Android Extensions ViewBinding works by default for Activity and Fragment.

import kotlinx.android.synthetic.main.activity_main.*

class TestActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Instead of findViewById<TextView>(R.id.textView)
        textView.setText("Hello world!")
    }
}

To make it work for ViewHolder in RecyclerView, use LayoutContainer.

Edit build.gradle (Module)

androidExtensions {
    // https://kotlinlang.org/docs/tutorials/android-plugin.html#experimental-mode
    experimental = true
}
class LocalListAdapter() : RecyclerView.Adapter<LocalListAdapter.ViewHolder>() {
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.apply {
            textView.text = "Hello"
        }
    }

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

NOTE: You can access view in ViewHolder by holder.itemView.textView (without LayoutContainer), but it doesn’t comes with View Caching

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.