I was trying to create an extension function to create object of view holder for recycler view adapter
inline fun <reified T: RecyclerView.ViewHolder> ViewGroup.createViewHolder(@LayoutRes res: Int): T {
val inflater = LayoutInflater.from(context)
val itemView = inflater.inflate(res, this, false)
// return ViewHolder Object
}
How do I create an object of the type T that extends RecyclerView.ViewHolder so that I can return from the function.
A clean alternative solution is to pass the constructor explicitly. It won't even be more verbose, because the type parameter can be inferred and doesn't need to be specified any more. Use like this:
val viewHolder = my_view_group.create(::MyViewHolder, R.layout.my_layout)
Implement like this:
inline fun <reified T: RecyclerView.ViewHolder> ViewGroup.create(createHolder: (View) -> T, @LayoutRes res: Int): T {
val inflater = LayoutInflater.from(context)
val itemView = inflater.inflate(res, this, false)
return createHolder(itemView)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With