Reputation: 672
Android Studio shows the error
Unexpected implicit cast to CharSequence: layout tag was TextView
at this code
findViewById<TextView>(R.id.tv_name).text = "text"
If I write
(findViewById<TextView>(R.id.tv_name) as TextView).text = "text"
Everything is fine.
The question is why this happens? Doesn't findViewById<TextView>
already have type TextView
?
Upvotes: 3
Views: 1624
Reputation: 301
First of, Kotlin under the hood, just wraps up java findViewById method. Up to API 26 explicit cast was neccessary as method returned View, but now it returns . Check this answer No need to cast the result of findViewById?
If you dive into the source code, through invokations of findViewById, you'll get to Window.findViewById method, and if you look to description of it in documentation, you'll see one note there, which says that: "In most cases -- depending on compiler support -- the resulting view is automatically cast to the target class type. If the target class type is unconstrained, an explicit cast may be necessary." https://developer.android.com/reference/android/view/Window.html#findViewById(int)
I don't know what "unconstrained" actually means in this context, but as i understand, in some cases cast is required in others is not, so just deal with it. For example, i tried to add some param to ImageView and compiler didn't show any kind of warnings:
findViewById<ImageView>(R.id.iv).adjustViewBounds = true
Upvotes: 0
Reputation: 301
This is only warning of lint. You can ignore it with @SuppressLint("WrongViewCast")
. This happend because of usage of generic types from Java in Kotlin.
Upvotes: 0
Reputation: 179
You can directly use all the views using DataBinding. Less code and very advance feature of android. There are many articles for Android DataBinding. https://developer.android.com/topic/libraries/data-binding/index.html
Upvotes: 0
Reputation: 1295
You can use Kotlin Android Extensions
Kotlin Android Extensions are Kotlin plugin that will allow to recover views from Activities, Fragments and Views in an amazing seamless way.
you can directly use
tv_name.text = "text"
no need of findViewById
Reference https://antonioleiva.com/kotlin-android-extensions/
Upvotes: 1