Search code examples
androidandroid-studiokotlinkotlin-android-extensionsandroid-viewbinding

TextView issues after migrate from Kotlin synthetics to Jetpack view binding


I recently migrate binding method from Kotlin synthetics to Jetpack view binding. I have AutofitTextView (by grantland) in my fragment and I set some text to the textview. After I started the activity and attached the fragment, the app crash. The error said

java.lang.ClassCastExceptioni: androidx.appcompt.widget.AppCompatTextView cannot be cast to me.grantland.widget.AutofitTextView

So, I decided to change from AutoFitTextView to AppCompatTextView but I face another issue. I cannot build the app because there is an error

Unresolve reference: setText

I tried various settext methods but none of them works. It seems that the TextView is seen as a View so it does not have a setText method.

========

Config details

  • Android Studio 4.1.2
  • buildToolsVersion 28.0.3
  • jvmTarget 1.8
  • com.android.databinding:compiler 3.1.4
  • androidx.appcommpat:appcompat:1.2.0

==========

fragment_main.xml

<FrameLayout
    .... >
    <LinearLayout
        .... >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <me.grantland.widget.AutofitTextView
                android:id="@+id/myTextView"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:text="This is textview" />
            ....
        </LinearLayout>
    </LinearLayout>
</FrameLayout>

Set text

FragmentMainBinding.myTextView.text = "The new text"


Solution

  • I found the cause!! It's my mistake. I have 2 layouts with the same name, one for portrait and another one for landscape. I migrate the views in portrait layout but not in landscape layout so when binding class is generated, it generate the two different TextViews as View and View does not have "text" attribute. That's what the error said.