Search code examples
androidkotlinadapter

How to add different adapters to FastAdapter in android


I'm using the android FastAdapter library from mikepenz I have two adapters 1: AnimeAdapter : for displaying anime list 2: progress adapter : the one provided by the library

here is my AnimeItem for the AnimeAdapter:

open class AnimeItem(anime: Anime): AbstractItem<AnimeItem.ViewHolder>() {
    var name: String? = anime.name
    var nbEpisodes: String? = anime.nbEpisodes


    override val layoutRes: Int
        get() = R.layout.anime_item
    override val type: Int
        get() = R.id.anime_item_id

    override fun getViewHolder(v: View): ViewHolder {
        return ViewHolder(v)
    }

    class ViewHolder(view: View) : FastAdapter.ViewHolder<AnimeItem>(view) {
        var animeNameTv: TextView = view.findViewById(R.id.anime_item_anime_name)
        var animeEpisodesTv: TextView = view.findViewById(R.id.anime_item_nb_episodes)

        override fun bindView(item: AnimeItem, payloads: MutableList<Any>) {
            animeNameTv.text = item.name
            animeEpisodesTv.text = item.nbEpisodes
        }

        override fun unbindView(item: AnimeItem) {
            animeNameTv.text = null
            animeEpisodesTv.text = null
        }
    }
}

in my activity I tried to create the 2 adapter and add them to FastAdapter like this:

val animeAdapter = ItemAdapter<AnimeItem>()
val footerAdapter = ItemAdapter<ProgressItem>()
var fastAdapter = FastAdapter.with(listOf(animeAdapter, footerAdapter))

but I always get this error:

Type inference failed: Not enough information to infer parameter Item in

fun <Item : GenericItem /* = IItem<out RecyclerView.ViewHolder> */, A : IAdapter<*>> with(adapters: Collection<A>?) : FastAdapter<Item>

Please specify it explicitly.


Solution

  • If you look at the signature of with, you can see Item isn't used in its arguments and so can't be inferred from them. You can either specify return type with the Item you want

    val fastAdapter: FastAdapter<GenericItem> = FastAdapter.with(listOf(animeAdapter, footerAdapter))
    

    as in this example in README or pass type parameters explicitly

    val fastAdapter = FastAdapter.with<GenericItem, ItemAdapter<*>>(listOf(animeAdapter, footerAdapter))
    

    Honestly, looking at code and particularly at this cast

    fastAdapter.adapters.addAll(adapters as Collection<IAdapter<Item>>)
    

    makes me suspect the signature should be fixed to

    fun <Item : GenericItem> with(adapters: Collection<IAdapter<Item>>?): FastAdapter<Item>
    

    which won't have this problem.

    I posted this as an issue: https://github.com/mikepenz/FastAdapter/issues/838