微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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开始提供.

原文地址:https://www.jb51.cc/android/430166.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐