[英]Kotlin Type mismatch: inferred type is View! but TextView was expected
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: 在Android Studio 3.0
使用Kotlin
1.1.51,针对Android API 26
使用下一个ViewHolder
创建RecyclerView
,但在构建项目时收到错误:
Type mismatch: inferred type is View! 类型不匹配:推断类型是View! but TextView was expected 但TextView是预料之中的
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
直接到ViewHolder
变量,但找到了方法 - 找到View,然后使用as TextView
演员,你可以在holder.
的代码中看到holder.
textView. 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: 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)
}
It seems like you're not on API level 26 or newer yet. 您似乎还没有使用API级别26或更新版本。 That's when findViewById
was changed so that it returns a generic T
instead of the base View
class, which enables you to use it from Kotlin in these ways . 这是当findViewById
被更改以便它返回通用T
而不是基本View
类时,这使您能够以这些方式从Kotlin中使用它。
You can either manually cast the result of the findViewById
call as @AlexTa suggested in the other answer , or you can update your support library version to 26
or later - the latest currently is 27.0.0
. 您可以手动将findViewById
调用的结果转换为另一个答案中建议的@AlexTa,也可以将支持库版本更新为26
或更高版本 - 最新版本为27.0.0
。 These new versions are available from Google's Maven repository . 这些新版本可从Google的Maven存储库获得 。
You just need to cast found view as expected type, to do so: 您只需要将找到的视图转换为预期类型,即可:
val timeView: TextView = itemView.findViewById(R.id.timeline_item_time) as TextView
or 要么
val timeView: TextView = itemView.findViewById<TextView>(R.id.timeline_item_time)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.