在自定义view中使用kotlinx.android.synthetic是可以的,但是需要进行一些额外的步骤。

首先,在自定义view的构造函数中,需要调用View.inflate()方法来加载自定义view的布局文件。例如:

class MyCustomView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    init {
        View.inflate(context, R.layout.activity_main2, this)
        // 这里可以使用kotlinx.android.synthetic
        // 例如:textView.text = "Hello"
    }
}

然后,在使用自定义view的地方,需要在布局文件中正确地引用自定义view,并且使用全限定名来指定自定义view的包名。例如:

<com.example.MyCustomView
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

这样,就可以在自定义view的代码中使用kotlinx.android.synthetic了。

另外,记得在项目的build.gradle文件中引入kotlin-android-extensions插件:

apply plugin: 'kotlin-android-extensions'

如果还是遇到报错,可以尝试重新构建项目,或者清除编译缓存

android开发:自定义view中不能使用kotlinxandroidsynthetic吗我添加了import kotlinxandroidsyntheticmainactivity_main2view代码没报错但运行时会在_$_findCachedViewById里报错如果是在activity里使用就不报错、在自定义view里用就会报错!

原文地址: https://www.cveoy.top/t/topic/iYm2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录