Skip to content

Instantly share code, notes, and snippets.

@vladignatyev
Created May 21, 2018 12:50
Show Gist options
  • Save vladignatyev/acdd1e99be53f779e86082311008310f to your computer and use it in GitHub Desktop.
Save vladignatyev/acdd1e99be53f779e86082311008310f to your computer and use it in GitHub Desktop.
Kotlin + Anko + ButterKnife: helper for async adapter for ListView
package com.github.kotlin.lib
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import butterknife.ButterKnife
abstract class ListAdapter<T>(ctx: Context, private val itemView: Int, items: ArrayList<T>) : ArrayAdapter<T>(ctx, 0, items) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val item:T = getItem(position)
val view: View = convertView ?: (LayoutInflater.from(context))!!.inflate(itemView, parent, false)
ButterKnife.bind(this, view)
fulfillView(view, item)
return view
}
abstract fun fulfillView(view: View, item: T)
}
@vladignatyev
Copy link
Author

vladignatyev commented May 21, 2018

Wherever you need adapter for list (in the example below, the Topic is data object representing an item), you can make it easier, with ButterKnife bindings included:

class ItemsListAdapter(ctx: Context, items: ArrayList<Topic>) : ListAdapter<Topic>(ctx, R.layout.category_item, items) {
    @BindView(R.id.title)
    lateinit var title: TextView

    override fun fulfillView(view: View, item: Topic) {
        title.text = item.title
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment