How to declare generic RecyclerView adapter in Android

Issue #357

generic/Adapter.kt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.onmyway133.generic

import 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

1
2
3
4
5
6
7
8
9
10
11
12
13
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 https://stackoverflow.com/questions/49512629/default-interface-methods-are-only-supported-starting-with-android-n

app/build.gradle

1
2
3
4
5
6
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}

Comments