Good day!
Using Kotlin
1.1.51 in Android Studio 3.0
, targeting Android API 26
to create RecyclerView
with next ViewHolder
, but receiving error on building the project:
Type mismatch: inferred type is View! but TextView was expected
So I can't find TextView
directly to ViewHolder
variable, but found around way - find View and after that cast with as TextView
as you can see in the code for holder.
textView. Doesn't look so good, so are there solutions how to prevent this error or is it a bug?
The code of RecyclerView
.Adapter:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.custom_item_view, parent, false)
return VH(view)
}
override fun onBindViewHolder(holder: VH, position: Int) {
val event: TimelineEvent = items[position]
// does not work because of error in VH class
holder.timeView.text = event.time
// works
(holder.textView as TextView).text = event.text
}
class VH(itemView: View) : RecyclerView.ViewHolder(itemView) {
// error: Type mismatch: inferred type is View! but TextView was expected
val timeView: TextView = itemView.findViewById(R.id.timeline_item_time)
// works fine
val textView: View = itemView.findViewById(R.id.timeline_item_text)
}