>我有以下类
open abstract class NexusAdapter<TData: NexusIdProvider, TViewHolder: NexusViewHolder<TData>>
(protected val ctx: Context, private val _layoutId: Int, protected val items: List<TData>):
BaseAdapter() {
override fun getView(position: Int, view: View?, parent: ViewGroup?): View {
val itemView = if (view == null)
LayoutInflater.from(ctx).inflate(_layoutId, parent, false)
else view!!
// How do I create the object of type TViewHolder at runtime????
var viewHolder: TViewHolder = TViewHolder::class.java.newInstance()
viewHolder.bind(itemView , getItem(position))
return itemView
}
//...
}
如何在类中创建类型TViewHolder
的对象。
你不能这样做。您必须为其提供工厂方法。
要么在类中将其与抽象函数一起使用
abstract fun createViewHolder(): TViewHolder
或将其作为参数提供给构造函数
abstract class NexusAdapter<TData: NexusIdProvider, TViewHolder: NexusViewHolder<TData>>(
protected val ctx: Context,
private val _layoutId: Int,
protected val items: List<TData>,
private val createViewHolder: () -> TViewHolder
) : BaseAdapter()