3

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?

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
GuessWho
  • 664
  • 1
  • 6
  • 19

4 Answers4

1

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/

Naveen Dew
  • 1,295
  • 11
  • 19
0

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

Vatsal Desai
  • 169
  • 4
0

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.

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
  • I don't understand your explanation: "because of usage of generic types from Java in Kotlin." – Micha Wiedenmann Feb 20 '18 at 19:49
  • Because Kotlin thinks that you want to set value in wrong way. Use syntetics or such declaration: `(findViewById(R.id.tvLog)).text = ""` – Constantin Chernishov Feb 21 '18 at 11:20
  • Obviously I can only speak for myself, but neither your answer nor your comment were anywhere detailed enough for me to follow. If I am allowed I would kindly ask you to rewrite them with the goal of making them much precise and detailed. – Micha Wiedenmann Feb 21 '18 at 11:27
0

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
Dmitriy
  • 5,525
  • 12
  • 25
  • 38