I want to set a listener on RecyclerView items using RxJava2. The items are checkboxes. I want to listen to each item separately. So I am getting an error Constructor of inner class ViewHolder can be called only with receiver of containing class in the
return TraceAdapter.ViewHolder(view)
class TraceAdapter(private var checkList: List<TraceViewModelRow> = listOf()) :
RecyclerView.Adapter<TraceAdapter.ViewHolder>() {
private val publishSubject = PublishSubject.create<Event>()
val events: Observable<Event> = publishSubject
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TraceAdapter.ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_trace_task, parent, false)
return TraceAdapter.ViewHolder(view)
}
override fun getItemCount(): Int = checkList.size
override fun onBindViewHolder(holder: TraceAdapter.ViewHolder, position: Int) {
holder.bindTraceList(checkList[position])
}
override fun onViewRecycled(holder: ViewHolder) {
super.onViewRecycled(holder)
}
inner class ViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer {
fun bindTraceList(trace: TraceViewModelRow) {
with(trace) {
checkbox_itemText.clicks()
.map { checkList[layoutPosition] }
.subscribe { publishSubject }
checkbox_itemText.text = description
checkbox_itemText.isChecked = isChecked
}
}
}
}
I think you just need to change this line:
return TraceAdapter.ViewHolder(view)
to this:
return ViewHolder(view)
As you've explicitly marked it as an inner class, it requires an instance of the outer class, which you get by default because you're constructing it from within the outer class. However only if you don't prefix it with the outer class type, as shown above.
The distinction between inner and nested classes is a bit different in Kotlin and Java (Java uses the term static
for nested classes that don't have an instance of the outer class). It's explained in more detail here.