<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anton Shinkaretsky on Medium]]></title>
        <description><![CDATA[Stories by Anton Shinkaretsky on Medium]]></description>
        <link>https://medium.com/@antonshinkaretsky?source=rss-6f47891163e2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*vKqX7goN58ngjsh-Ta76BQ.jpeg</url>
            <title>Stories by Anton Shinkaretsky on Medium</title>
            <link>https://medium.com/@antonshinkaretsky?source=rss-6f47891163e2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:35:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@antonshinkaretsky/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The best Android Recycler Adapter you’ve ever seen. Probably]]></title>
            <link>https://proandroiddev.com/the-best-android-recycler-adapter-youve-ever-seen-probably-177e25279a28?source=rss-6f47891163e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/177e25279a28</guid>
            <category><![CDATA[adapter]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Anton Shinkaretsky]]></dc:creator>
            <pubDate>Sun, 10 Nov 2019 06:44:58 GMT</pubDate>
            <atom:updated>2019-11-11T05:36:20.415Z</atom:updated>
            <content:encoded><![CDATA[<p>Composable, and also the shortest Android Recycler Adapter you could dream of. And I assure you, as soon as you make it only once, you will love it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c-mVpLk_ubDbS3oINWsYow.png" /></figure><p>All you need to setup your Adapter in most cases is (MovieCell, LoadingCell, ErrorCell are types of a cell here):</p><pre>class MoviesListAdapter(listener: AdapterListener): BaseListAdapter(<br>        <strong>MovieCell</strong>, LoadingCell, ErrorCell,<br>        listener = listener<br>)</pre><p>All you need to create a new type of a Cell in most cases is:</p><pre>object <strong>MovieCell</strong> : Cell&lt;RecyclerItem&gt;() {<br><br>    override fun<strong> </strong>belongsTo(item: RecyclerItem?): Boolean {<br>        return item is <strong>Movie</strong><br>    }<br><br>   <strong> </strong>override fun<strong> </strong>type(): Int {<br>        return <strong>R.layout</strong>.<strong><em>item_movie</em></strong><em><br>    </em>}<br><br>    override fun<strong> </strong>holder(parent: ViewGroup):RecyclerView.ViewHolder {<br>        return <strong>MovieViewHolder</strong>(parent.<em>viewOf</em>(type()))<br>    }<br><br>    override fun<strong> </strong>bind(<br>        holder: RecyclerView.ViewHolder,<br>        item: RecyclerItem?,<br>        listener: AdapterListener?<br>    ) {<br><br>        if (holder is <strong>MovieViewHolder</strong> &amp;&amp; item is <strong>Movie</strong>)<strong> </strong>{<strong><br></strong>            holder.bind(item)<strong><br>            holder.itemView.setOnClickListener {<br>                listener?.listen(item)<br>            }<br>        </strong>}<strong><br>    </strong>}</pre><pre>}</pre><p>This solution not only doesn’t have switches, scattered through 3 different methods (getItemViewType, onCreateViewHolder, onBindViewHolder), but is clean, short and expressive, and it allows you to compose Adapters from different sets of Cells.</p><p>It’s adaptable for RecyclerView.Adapter, ListAdapter, and also paging library PagedListAdapter. You only have to create new BaseAdapter for each.</p><p>Content:</p><p>1. I’ll give the code to copy to make it work.<br>2. I’ll explain step by step how to use it.<br>3. For curious ones, we’ll dig into the details.<br>4. Conclusion</p><p><a href="https://github.com/AntonShinkaretsky/AwesomeAdapterExample">Click to see an example project</a>.</p><h3>What I have to copy to make it work</h3><p>Below there is a set of abstractions that will allow you to create Adapters as simple and convenient as above.</p><p>Cell that represents, well, an Adapter cell:</p><pre>abstract class <strong>Cell</strong>&lt;T&gt; {<br><br>    abstract fun belongsTo(item: T?): Boolean<br>    abstract fun type(): Int<br>    abstract fun holder(parent: ViewGroup): RecyclerView.ViewHolder<br>    abstract fun bind(holder: RecyclerView.ViewHolder, item: T?, listener: AdapterListener?)<br><br>    protected fun ViewGroup.viewOf(@LayoutRes resource: Int): View {<br>        return LayoutInflater<br>                .from(<em>context</em>)<br>                .inflate(resource, this, false)<br>    }<br><br>}</pre><p>CellTypes class that represents a set of Cells, that is available for Adapter:</p><pre>class <strong>CellTypes</strong>&lt;T&gt;(vararg types: Cell&lt;T&gt;) {<br><br>    private val cellTypes: ArrayList&lt;Cell&lt;T&gt;&gt; = ArrayList()<br><br>    init {<br>        types.<em>forEach </em>{ addType(it) }<br>    }<br><br>    fun addType(type: Cell&lt;T&gt;) {<br>        cellTypes.add(type)<br>    }<br><br>    fun of(item: T?): Cell&lt;T&gt; {<br>        for (cellType in cellTypes) {<br>            if (cellType.belongsTo(item)) return cellType<br>        }<br>        throw NoSuchRecyclerItemTypeException()<br>    }<br><br>    fun of(viewType: Int): Cell&lt;T&gt; {<br>        for (cellType in cellTypes) {<br>            if (cellType.type() == viewType) return cellType<br>        }<br>        throw NoSuchRecyclerViewTypeException()<br>    }<br><br>}</pre><p>BaseListAdapter, which in our example extends recyclerview.extensions.ListAdapter</p><p>(you can also apply the same approach for RecyclerView.Adapter, as well as for paging library PagedListAdapter)</p><pre>abstract class <strong>BaseListAdapter</strong>(<br>        vararg types: Cell&lt;RecyclerItem&gt;,<br>        private val listener: AdapterListener? = null<br>) : ListAdapter&lt;RecyclerItem, RecyclerView.ViewHolder&gt;(<em>BASE_DIFF_CALLBACK</em>) {<br><br>    private val cellTypes: CellTypes&lt;RecyclerItem&gt; = CellTypes(*types)<br><br>    override fun getItemViewType(position: Int): Int {<br>        val item = getItem(position)<br>        return cellTypes.of(item).type()<br>    }<br><br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {<br>        return cellTypes.of(viewType).holder(parent)<br>    }<br><br>    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {<br>        val item = getItem(position)<br>        cellTypes.of(item).bind(holder, item, listener)<br>    }<br><br>}</pre><p>RecyclerItem that represents an object passed to the adapter that will be converted to a Cell:</p><pre>interface <strong>RecyclerItem </strong>{<br>    val id: String?<br>    override fun equals(other: Any?): Boolean<br>}</pre><p>Two interfaces for communication between your adapter and a view that holds it:</p><pre>interface <strong>AdapterListener </strong>{<br>    fun listen(click: AdapterClick?)<br>}</pre><pre>interface <strong>AdapterClick</strong></pre><p>And base diff that works with it:</p><pre>val <strong><em>BASE_DIFF_CALLBACK </em></strong>= object : DiffUtil.ItemCallback&lt;<strong>RecyclerItem</strong>&gt;() {<br><br>    override fun areItemsTheSame(oldItem: <strong>RecyclerItem</strong>, newItem: <strong>RecyclerItem</strong>): Boolean {<br>        return oldItem.<strong>id </strong>== newItem.<strong>id</strong><br>    }<br><br>    override fun areContentsTheSame(oldItem: <strong>RecyclerItem</strong>, newItem: <strong>RecyclerItem</strong>): Boolean {<br>        return oldItem == newItem<br>    }<br><br>}</pre><p>And two Exceptions:</p><pre>class <strong>NoSuchRecyclerItemTypeException </strong>: RuntimeException()<br>class <strong>NoSuchRecyclerViewTypeException </strong>: RuntimeException()</pre><p>That’s pretty much it.</p><h3>How do I use it?</h3><p>Let’s try it taking “Movie” as an example.</p><h4>1. Implement a Cell</h4><ul><li>In <em>belongsTo()</em> there should be an object that you are converting into a list cell</li><li>In <em>type() </em>there should be a layout for this object</li><li>In <em>holder()</em> there should be a RecyclerView.ViewHolder for this cell</li><li>In <em>bind()</em> you bind info to the cell, add click listeners, change background, etc</li></ul><pre>object <strong>MovieCell </strong>: Cell&lt;RecyclerItem&gt;() {<br><br>    override fun belongsTo(item: RecyclerItem?): Boolean {<br>        return item is <strong>Movie</strong><br>    }<br><br>    override fun type(): Int {<br>        return R.layout.<strong><em>item_movie</em></strong><em><br>    </em>}<br><br>    override fun holder(<br>        parent: ViewGroup<br>    ): RecyclerView.ViewHolder {<br>        return <strong>MovieViewHolder</strong>(parent.<em>viewOf</em>(type()))<br>    }<br><br>    override fun bind(<br>        holder: RecyclerView.ViewHolder,<br>        item: RecyclerItem?,<br>        listener: AdapterListener?<br>    ) {<br><br>        if (holder is <strong>MovieViewHolder </strong>&amp;&amp; item is <strong>Movie</strong>) {<br>            holder.bind(item)<br>            <strong>holder.itemView.setOnClickListener {<br>                listener?.listen(item)<br>            }</strong><br>        }<br>    }<br><br>}</pre><p>I advise to keep all info binding logic inside a ViewHolder’s method bind() to make it reusable even if you use the same view outside of a recycler’s adapter.</p><p>(In example above, besides info binding, I added a listener to the whole cell. When the cell is clicked, listener will get an object of corresponding <strong>Movie</strong>)</p><h4>2. Object class, 3. Layout for this object, 4. ViewHolder</h4><p>Implementation of the steps above I leave up to you. Remember, that movie should implement <strong>RecyclerItem </strong>and <strong>AdapterClick </strong>interfaces. Second one, if you want to listen clicks on items, or inside them.</p><p>If you have any questions, feel free to write comments. I’ll try to help, or improve the article.</p><h4>5. Create Adapter</h4><pre>class <strong>MovieAdapter</strong>(listener: AdapterListener) : BaseListAdapter(<br>    MovieCell,<br>    listener = listener<br>)</pre><h4>6. Implement listener</h4><p>Inside your Fragment (Activity, or any other view that contains recycler), create adapter, passing listener inside:</p><pre><strong>override fun </strong>listen(click: AdapterClick?) {<br>    <strong>when </strong>(click) {<br>        <strong>is </strong>Movie -&gt; <em>// E.g. open movie details<br>    </em>}<br>}</pre><p>Initialize recycler, pass a list of movies inside the adapter.</p><p>And that’s actually it. Now you can add other types of a cell, including such often used ones as LoadingCell or ErrorCell. And all these cells are totally reusable throughout all the adapters.</p><h4>Congrats, you’ve done it!</h4><h3>Let’s dive into a little detail</h3><p>Why have I spent time on such a thing at all? As we all do, I wanted to get rid of boilerplate code.</p><h4>Traditional approach</h4><p>I believe the vast majority is familiar with this basic type of adapter created to display several types of a cell:</p><pre>override fun getItemViewType(position: Int): Int {<br>    val item = list.get(position)<br>    return if (item is <strong>Movie</strong>) {<br>        <strong>TYPE_MOVIE</strong><br>    } else if (item is Progress) {<br>        TYPE_PROGRESS<br>    } else if (item is Error) {<br>        TYPE_ERROR<br>    } else {<br>        throw NoSuchRecyclerItemTypeException()<br>    }<br>}</pre><p>and</p><pre>override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {<br>    val inflater = LayoutInflater.from(parent.<em>context</em>)<br>    if (viewType == <strong>TYPE_MOVIE</strong>) {<br>        val view = inflater.inflate(R.layout.<strong>item_movie</strong>, parent, false)<br>        return <strong>MovieViewHolder</strong>(view)<br>    } else if (viewType == TYPE_PROGRESS) {<br>        val view = inflater.inflate(R.layout.item_progress, parent, false)<br>        return ProgressViewHolder(view)<br>    } else if (viewType == TYPE_ERROR) {<br>        val view = inflater.inflate(R.layout.item_error, parent, false)<br>        return ErrorViewHolder(view)<br>    } else {<br>        throw NoSuchRecyclerViewTypeException()<br>    }<br>}</pre><p>and also</p><pre>override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {<br>    if (holder is <strong>MovieViewHolder</strong>) {<br>        (holder as <strong>MovieViewHolder</strong>).bind(list.get(position) as <strong>Movie</strong>)<em><br>    </em>} else if (holder is AdViewHolder) {<br>        (holder as ErrorViewHolder).bind(list.get(position) as Error)<br>    } else if (holder is ProgressViewHolder) {<br>        <em>// Do nothing<br>    </em>}<br>}</pre><p>I think most of you will agree, that it’s hard to read, hard to maintain. It’s error-prone, because every time you need a change you have to make it in 3 places. And it’s just ugly, and a hell lot of a code. You also have to duplicate code for identical cells in different adapters. This is how I did it, this is how most of us did it at a certain point.</p><p>Then I came across better solutions.</p><h4>Improved approaches</h4><p>Alternative options I saw resolved some problems. Usually they kept code for one cell in one place, that was a really great improvement.</p><p>As an example, we have Adapter, that goes through an Enum called <strong>CellType</strong>:</p><pre>override fun getItemViewType(position: Int): Int {<br>    return <strong>CellType[list.get(position)].type()</strong><br>}<br><br>override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {<br>    return <strong>CellType[viewType].holder(parent)</strong><br>}<br><br>override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {<br>    val item = list.get(position)<br>    <strong>CellType[item].bind(holder, item)</strong><br>}</pre><p>CellType contains four abstract methods for cells to implement, and two other for finding a necessary cell:</p><pre>private enum class CellType {</pre><pre>    internal abstract fun <strong>`is`(item: Any): Boolean</strong><br>    internal abstract fun <strong>type(): Int</strong><br>    internal abstract fun <strong>holder(parent: ViewGroup): RecyclerView.ViewHolder</strong><br>    internal abstract fun <strong>bind(holder: RecyclerView.ViewHolder, item: Any)</strong></pre><pre>    companion object {<br>        internal operator fun <strong>get(item: Any): CellType</strong> {<br>            for (cellType in values()) {<br>                if (cellType.`is`(item)) return cellType<br>            }<br>            throw NoSuchRecyclerItemTypeException()<br>        }</pre><pre>        internal operator fun <strong>get(viewType: Int): CellType</strong> {<br>            for (cellType in values()) {<br>                if (cellType.type() == viewType) return cellType<br>            }<br>            throw NoSuchRecyclerViewTypeException()<br>        }<br>    }<br>}</pre><p>That CellType also contains cells similar to the following one:</p><pre><strong>MOVIE {</strong><br>  override fun `is`(item: Any): Boolean {<br>     return item is <strong>Movie</strong><br>  }<br><br>  override fun type(): Int {<br>     return R.layout.<strong>item_movie</strong><br>  }<br><br>  override fun holder(parent: ViewGroup): RecyclerView.ViewHolder {<br>     val inflater = LayoutInflater.from(parent.<em>context</em>)<br>     val view = inflater.inflate(R.layout.<strong>item_movie</strong>, parent, false)<br>     return <strong>MovieViewHolder</strong>(view)<br>  }<br><br>  override fun bind(holder: RecyclerView.ViewHolder, item: Any) {<br>     if (holder is <strong>MovieViewHolder </strong>&amp;&amp; item is <strong>Movie</strong>) {<br>       holder.bind(item)<br>     }<br>  }<br><strong>}</strong>;</pre><p>The example above, together with my whole approach, was inspired by <a href="https://habr.com/ru/post/320242/">this article</a>. And it was a huge breakthrough. It looks much cleaner, since all the code related to the cell is inside corresponding Enum type.</p><p>But copying the rest of the logic from adapter to adapter really bothered me, I felt there was a room for improvement. Because in 95% of cases I just changed nothing but cells, and copy-pasted cells such as Loading and Error from one adapter to another.</p><p>So I wanted to erase duplication of logic, and also make something composable so that not to duplicate identical cells.</p><h4>Development</h4><ol><li>Replaced an Enum (that is not composable) inside adapters with a list, hosting cells that implement a Cell interface. All “getItemViewType, onCreateViewHolder, onBindViewHolder” logic was placed inside base adapter called <strong>BaseListAdapter</strong>.</li><li>Took all the logic that picks corresponding cell based on its object or layout, and placed it inside the list called <strong>CellTypes</strong>. That erased type-picking duplication.</li><li>Deleted all repetitive code I could get rid of inside the <strong>Cell</strong>. Now I was forced to follow simpler interface for cell creation.</li><li>Separated click-handling logic from Adapter through AdapterListener interface.</li></ol><p>I could use <strong>Any? </strong>with AdapterListener, since <strong>AdapterClick </strong>interface is empty. But based on my understanding of the process of casting it’s better for performance to have interface with limited amount of inheritors. I can be wrong here, please feel free to correct me.</p><h3>Conclusion</h3><p>Everything else was just polishing that led to super-minimalistic declarative way of adapter creation that also allows you to compose your adapters just like some constructor.</p><p>As for now, in absolute majority of cases we have <a href="https://www.kapowai.online/en/">here in Kapowai</a>, we don’t need to do anything else, because approach is flexible enough.</p><p>Of course these solutions can be improved further. I see the highest potential in Cell class. And I’ll be happy to hear any feedback on solution code. But I sincerely hope I’ll help some of you, saving your time and giving you joy — the joy I’ve felt every time since I started using this approach while creating new adapter :)</p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=177e25279a28" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/the-best-android-recycler-adapter-youve-ever-seen-probably-177e25279a28">The best Android Recycler Adapter you’ve ever seen. Probably</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>