Skip to content

Instantly share code, notes, and snippets.

@timmutton
Created March 8, 2018 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timmutton/99af8b5a7ef95752a7159c83f81b3ae1 to your computer and use it in GitHub Desktop.
Save timmutton/99af8b5a7ef95752a7159c83f81b3ae1 to your computer and use it in GitHub Desktop.
SimpleRecyclerViewAdapter
package au.com.realestate.hometime.presentation.common
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
class SimpleRecyclerViewAdapter<T>(private val itemType: Class<SimpleRecyclerViewAdapter.ViewDataBinding<T>>,
private val items: List<T>) : RecyclerView.Adapter<SimpleRecyclerViewAdapter.SimpleViewHolder<T>>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SimpleViewHolder<T> {
val view = itemType.getConstructor().newInstance()
view.inflate(parent)
return SimpleViewHolder(view)
}
override fun onBindViewHolder(holder: SimpleViewHolder<T>, position: Int) =
holder.bindableItem.bind(items[position])
override fun getItemCount(): Int = items.size
class SimpleViewHolder<T>(val bindableItem: ViewDataBinding<T>) : RecyclerView.ViewHolder(bindableItem.getRoot())
interface ViewDataBinding<T> {
fun getRoot(): View
fun inflate(parent: ViewGroup, attachToParent: Boolean = true)
fun bind(item: T)
}
}
@mochadwi
Copy link

mochadwi commented Apr 6, 2019

Any updates on this @timmutton

@timmutton
Copy link
Author

Unfortunately it doesnt look like I can edit it any more, and im not sure what I wanted to change about it 14 months ago, but off the top of my head I'd probably do:

class SimpleRecyclerViewAdapter<T>(private val itemType: Class<SimpleRecyclerViewAdapter.ViewDataBinding<T>>,
                                   private val items: List<T>) : RecyclerView.Adapter<SimpleRecyclerViewAdapter.SimpleViewHolder<T>>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SimpleViewHolder<T> {
        val view = itemType.getConstructor().newInstance()
        return SimpleViewHolder(view)
    }

    override fun onBindViewHolder(holder: SimpleViewHolder<T>, position: Int) =
            holder.bindableItem.bind(items[position])

    override fun getItemCount(): Int = items.size

    class SimpleViewHolder<T>(val bindableItem: ViewDataBinding<T>) : RecyclerView.ViewHolder(bindableItem.inflate())

    interface ViewDataBinding<T> {
        fun inflate(parent: ViewGroup): View
        fun bind(item: T)
    }
}

and perhaps some error handling for the reflection based initialisation like:

init {
   if(itemType.constructors.none { it.parameterTypes.isEmpty() }){
      // handle no constructor
   }
}

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