Skip to content

Instantly share code, notes, and snippets.

@hovi
Last active September 21, 2018 13:15
Show Gist options
  • Save hovi/193afafa19ab2ca04b4c394e5c097915 to your computer and use it in GitHub Desktop.
Save hovi/193afafa19ab2ca04b4c394e5c097915 to your computer and use it in GitHub Desktop.
//Adapter for RecyclerView, that displays contents of kotlin data class using reflection (or in theory just public properties of a class).
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
import kotlin.reflect.KVisibility
import kotlin.reflect.full.memberProperties
val <T : Any> KClass<T>.publicProperties: Collection<KProperty1<T, *>>
get() = memberProperties.filter { it.visibility == KVisibility.PUBLIC }
class DataClassAdapter<T : Any>(val data: T) : RecyclerView.Adapter<DataClassAdapter.MyViewHolder>() {
private val properties: List<KProperty1<*, *>>
init {
properties = data::class.publicProperties.toList()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val textView = LayoutInflater.from(parent.context)
.inflate(R.layout.row, parent, false) as TextView
return MyViewHolder(textView)
}
override fun getItemCount(): Int {
return properties.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val property = properties[position]
val value = property.getter.call(data)
onBindViewHolder(holder, property.name, value)
}
fun onBindViewHolder(holder: MyViewHolder, name: String, value: Any?) {
holder.textView.text = name + " - " + value.toString()
}
class MyViewHolder(val textView: TextView) : RecyclerView.ViewHolder(textView)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment