Skip to content

Instantly share code, notes, and snippets.

@venator85
Created August 25, 2018 08:13
Show Gist options
  • Save venator85/a381abdcef25d242d30f5553c44be958 to your computer and use it in GitHub Desktop.
Save venator85/a381abdcef25d242d30f5553c44be958 to your computer and use it in GitHub Desktop.
RecyclerView with item click support
package eu.alessiobianchi
import android.support.v7.widget.RecyclerView
import android.view.View
interface ItemClickListener<T> {
fun onClick(view: View, position: Int, item: T)
}
abstract class ClickableAdapter<T, V: ClickableViewHolder<T>>(
private val itemClickListener: ItemClickListener<T>
) : RecyclerView.Adapter<V>() {
var items: List<T> = emptyList()
private set
internal fun onItemClick(view: View, position: Int) {
itemClickListener.onClick(view, position, items[position])
}
fun update(items: List<T>) {
this.items = items
onNewData(items)
notifyDataSetChanged()
}
open fun onNewData(items: List<T>) {
}
final override fun getItemCount() = items.size
}
open class ClickableViewHolder<T>(
row: View,
private val clickableAdapter: ClickableAdapter<T, out ClickableViewHolder<T>>
) : RecyclerView.ViewHolder(row), View.OnClickListener {
init {
@Suppress("LeakingThis")
row.setOnClickListener(this)
}
final override fun onClick(v: View) {
adapterPosition.let {
if (it != RecyclerView.NO_POSITION) {
clickableAdapter.onItemClick(v, it)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment