Kotlin Android Extensions with ViewHolders

Something I recently discovered is how easy it is to use Kotlin’s Android View extensions with RecyclerView ViewHolders. Previously using Butterknife, many of my ViewHolder classes were simply a bunch of @BindViews with an init { ButterKnife.bind } . With Kotlin Android extensions, the views are declared as extensions on the ViewHolder’s ItemView field. Additionally, instead of declaring a ViewHolder class with one line, you can actually just use an anonymous object in your onCreateViewHolder method.

You could potentially use any of Kotlin’s scoping extension functions, I prefer to use let, so here’s what that looks like (note also the this[...] notation) :

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        object : RecyclerView.ViewHolder(
            context.inflate(R.layout.adapter_thread, parent)
        ) {}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val item = this[position]
    holder.itemView.let {
        it.viewIdTitle = item.title
        it.viewIdDescription = item.description

class ViewHolder(v: View) : RecyclerView.ViewHolder(v)

Author: awscherb

Android guy

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s