ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Follow publication

SyntheticViewHolder: A Kotlin Android Extensions LayoutContainer

Christian Schmitz
ProAndroidDev
Published in
2 min readNov 2, 2020

--

Photo by Rubén Bagüés on Unsplash

The RecyclerView.ViewHolder describes an item view and metadata about its place within the RecyclerView. Also it is responsible for caching potentially expensive View.findViewById(int) call results. In combination with the same synthetic properties that provide access to layout specific views of activities and fragments, this is basically the purpose of the Kotlin Android Extensions LayoutContainer type.

A base interface for all view holders supporting Android Extensions-style view access.

Combining the ViewHolder and the LayoutContainer in one type, provides a powerful tool for all RecyclerView.Adapter implementations with Kotlin.

@ContainerOptions(SPARSE_ARRAY)
open class SyntheticViewHolder(
override val containerView: View
) : ViewHolder(
containerView
), LayoutContainer

The main advantage here is, that the ViewHolder itself handles the caching of the views and does not know about the structure of the view or the items bound to it. There is no inversion of responsibility and the Adapter is solely responsible for creating and binding the view hierarchy.

Anyhow, the ViewHolder pattern is exactly this: a pattern. Everything required is an itemView to be passed to the constructor. Everything else is up to the developer to decide. It could even store metadata related to the currently bound item or metadata about the layout represented by the ViewHolder itself.

open class SyntheticLayoutHolder(
@LayoutRes val layoutRes: Int,
parent: ViewGroup
) : SyntheticViewHolder(
from(parent.context).inflate(
layoutRes,
parent,
false
)
)

These two ViewHolder types provide a good basis for most of the use-cases developers might encounter, even if they will come up with use-cases they need to create different standalone or descended ViewHolder implementations. But thanks to synthetic properties and the SyntheticViewHolder, no developer needs to concern themself with the layout anymore.

Just never use synthetic properties with the itemView directly. These will not cache the resolved views and call findViewById(id) with every call to the binding function.

So, enjoy coding!

--

--

Published in ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Responses (6)

Write a response