How to declare generic RecyclerView adapter in Android

Khoa Pham
Khoa Pham
Nov 6, 2019 · 1 min read

generic/Adapter.kt

package com.onmyway133.genericimport android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
abstract class Adapter<T>(var items: ArrayList<T>): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
abstract fun configure(item: T, holder: ViewHolder)
fun update(items: ArrayList<T>) {
this.items = items
notifyDataSetChanged()
}
override fun getItemCount(): Int = items.count() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val view = LayoutInflater
.from(parent.context)
.inflate(viewType, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
configure(items[position], holder as ViewHolder)
}
}class ViewHolder(view: View): RecyclerView.ViewHolder(view) {}

hero/HeroAdapter.kt

package com.onmyway133.hero
import kotlinx.android.synthetic.main.hero_item_view.view.*
class Adapter(items: ArrayList<Hero>): com.onmyway133.generic.Adapter<Hero>(items) {
override fun configure(item: Hero, holder: ViewHolder) {
holder.itemView.titleLabel.text = item.name
holder.itemView.descriptionLabel.text = item.description
}
override fun getItemViewType(position: Int): Int {
return R.layout.hero_item_view
}
}

May run into stackoverflow.com/questions/49512629/default-interface-methods-are-only-supported-starting-with-android-n

app/build.gradle

android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}

Fantageek

Simple apps that make sense

Khoa Pham

Written by

Khoa Pham

My apps https://onmyway133.github.io/

Fantageek

Fantageek

Simple apps that make sense

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade