繁体   English   中英

从 Kotlin 合成迁移到 Jetpack 视图绑定后出现 TextView 问题

[英]TextView issues after migrate from Kotlin synthetics to Jetpack view binding

我最近将绑定方法从 Kotlin 合成迁移到 Jetpack 视图绑定。 我的片段中有 AutofitTextView(by grantland),我将一些文本设置为 textview。 在我开始活动并附加片段后,应用程序崩溃了。 错误说

java.lang.ClassCastExceptioni: androidx.appcompt.widget.AppCompatTextView 不能转换为 me.grantland.widget.AutofitTextView

因此,我决定从 AutoFitTextView 更改为 AppCompatTextView 但我面临另一个问题。 我无法构建应用程序,因为出现错误

未解决参考:setText

我尝试了各种 settext 方法,但没有一个有效。 似乎 TextView 被视为视图,因此它没有 setText 方法。

========

配置详情

  • Android Studio 4.1.2
  • 构建工具版本 28.0.3
  • jvmTarget 1.8
  • com.android.databinding:编译器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>

设置文本

FragmentMainBinding.myTextView.text = "新文本"

我找到了原因。,这是我的错误。 我有 2 个具有相同名称的布局,一个用于纵向,另一个用于横向。 我以纵向布局而不是横向布局迁移视图,因此在绑定 class 时会生成。 它生成两个不同的 TextView,因为 View 和 View 没有“文本”属性。 这就是错误所说的。

试试这个样本。

val binder =  FragmentMainBinding.bind(View.inflate(requireContext(), R.layout.fragment_main, null))

binder.myTextView.text = "The new text"

因此,如果那是fragment_main.xml的整个 xml ,则需要用<layout>标记将所有内容包装起来。 这是编译器知道构建绑定类的唯一方法。

<layout
  ...>
    <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>
</layout>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM