android – Kotlin类型不匹配:推断类型是View!但TextView是预料之中的

美好的一天!
Android Studio 3.0中使用Kotlin 1.1.51,针对Android API 26使用下一个ViewHolder创建RecyclerView,但在构建项目时收到错误

Type mismatch: inferred type is View! but TextView was expected

所以我找不到TextView直接到ViewHolder变量,但找到了方法 – 找到View,然后使用TextView进行转换,你可以在holder.textView的代码中看到.看起来不那么好,那么有没有解决方法如何防止这个错误或者它是一个错误
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)
    }
最佳答案
您似乎还没有使用API​​级别26或更新版本.这是在更改find​​ViewById以便它返回通用T而不是基本View类时,这使您可以在these ways中使用Kotlin.

您可以手动将findViewById调用的结果转换为other answer中建议的@AlexTa,也可以将支持库版本更新为26或更高版本 – 最新版本为27.0.0.这些新版本可从Google’s Maven repository开始提供.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...