Created
March 8, 2018 12:08
-
-
Save timmutton/99af8b5a7ef95752a7159c83f81b3ae1 to your computer and use it in GitHub Desktop.
SimpleRecyclerViewAdapter
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 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) | |
} | |
} |
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
Any updates on this @timmutton