Skip to content

Instantly share code, notes, and snippets.

  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save johnnylambada/26dfd02262a58ac0eb63199ea68d253d to your computer and use it in GitHub Desktop.
Make RecyclerView with Anko Like Pro
abstract class AnkoRecyclerViewAdapter<Model : Any, AnkoView : AnkoComponent<ViewGroup>, ViewHolder : RecyclerView.ViewHolder> : RecyclerView.Adapter<ViewHolder>() {
abstract val data: List<Model> // Data list
abstract val ankoView: AnkoView // Layout as AnkoComponent<ViewGroup>
abstract fun ViewHolder.setup(model: Model) // setup model from ViewHolder
abstract val onItemClickListenerUnit: (Model) -> Unit // Item Click Listener
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.setup(data[position])
holder.itemView.setOnClickListener {
onItemClickListenerUnit.invoke(data[position])
}
}
override fun getItemCount() = data.size
// Must get ViewHolder from ViewGroup's tag
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int)
= ankoView.create(parent.context, parent).tag as ViewHolder
}
fun <T> AnkoComponent<T>.create(context : Context, t : T) = createView(AnkoContext.Companion.create(context, t))
// Show how to with simple example
// This is data model
data class Person(var name : String, var phoneNumber : String)
// This is RecyclerViewAdapter which extends AnkoRecyclerViewAdapter
class PersonListAdapter(list: List<Person>) : AnkoRecyclerViewAdapter<Person, PersonListItemView, PersonListViewHolder>() {
override lateinit var onItemClickListenerUnit: (Person) -> Unit
override val data = list
override val ankoView = PersonListItemView()
override fun PersonListViewHolder.setup(person: Person) {
titleTextView.text = person.name
subtitleTextView.text = person.phoneNumber
}
}
// Make your own list item view
class PersonListItemView : AnkoComponent<ViewGroup> {
lateinit var titleTextView: TextView
lateinit var subtitleTextView: TextView
override fun createView(ui: AnkoContext<ViewGroup>) = with(ui) {
cardView {
useCompatPadding = true
preventCornerOverlap = true
verticalLayout {
padding = dip(24)
titleTextView = textView().lparams(matchParent) { bottomMargin = dip(6) }
subtitleTextView = textView().lparams(matchParent)
}
// Set tag as PersonListViewHolder, Put view as parameters
tag = PersonListViewHolder(this, titleTextView, subtitleTextView)
}
}
}
// This is View Holder. Pass views which you want to modify
class PopconListViewHolder(view: View,
var titleTextView: TextView,
var subtitleTextView: TextView) : RecyclerView.ViewHolder(view)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment