Created
August 25, 2018 08:13
-
-
Save venator85/a381abdcef25d242d30f5553c44be958 to your computer and use it in GitHub Desktop.
RecyclerView with item click support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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