意外的隐式转换为CharSequence:布局标签是TextView

Android Studio显示错误Unexpected implicit cast to CharSequence: layout tag was TextView此代码中的Unexpected implicit cast to CharSequence: layout tag was TextView

 findViewById(R.id.tv_name).text = "text" 

如果我会写

 (findViewById(R.id.tv_name) as TextView).text = "text" 

一切安好。

问题是为什么发生这种情况? 不findViewById已经有TextViewtypes?

您可以使用Kotlin Android Extensions

Kotlin Android扩展程序是Kotlin插件,可以以惊人的无缝方式从活动,碎片和视图中恢复视图。

你可以直接使用

 tv_name.text = "text" 

不需要findViewById

参考https://antonioleiva.com/kotlin-android-extensions/

您可以使用DataBinding直接使用所有视图。 较少的代码和非常先进的function的机器人。 Android DataBinding有很多文章。 https://developer.android.com/topic/libraries/data-binding/index.html

“这只是lint的警告,你可以用@SuppressLint(”“WrongViewCast”“)来忽略它,这是由于在Kotlin中使用Java的genericstypes而发生的。