Kotlin Android 从未使用过扩展生成的函数

Kotlin Android Extensions generated functions are never used

我注意到 Kotlin Android 扩展的合成属性在某些情况下工作起来有些奇怪。在我的活动中使用它们还没有造成任何问题,但在视图持有者中它只是不断调用 findViewById() 而不是 _$_findCachedViewById() 。请注意,我使用的是最新的 Android Studio 和最新的插件(以及最新的 Kotlin 版本)。

所以,有这样一段代码:

class Holder(override val containerView: View) :
    RecyclerView.ViewHolder(containerView), LayoutContainer {
fun bind() {
    containerView.my_text_view.text = "Hello Whosebug!"
    itemView.my_another_view.text = "Foo"
    }
}

Java 中以下代码对我的结果:

TextView var10000 = (TextView)this.getContainerView().findViewById(id.my_text_view);
...
var10000 = (TextView)var1.findViewById(id.my_another_view);
...

据我所知,这与视图缓存无关,所以这是个问题。最有意思的是代码中生成了_$_findCachedViewById()_$_clearFindViewByIdCache()方法do,但是并没有使用。

即使在从网络下载的项目中,以下问题仍然存在。

我认为这是某种错误吗?生成的 Java 代码是否真的按预期工作?

The View Caching documentation 指出缓存仅在 ActivityFragmentViewLayoutContainer:

上完成

By default, Android Extensions adds a hidden cache function and a storage field to each container (Activity, Fragment, View or a LayoutContainer implementation) written in Kotlin.

所以你需要用你的 viewholder 实现 kotlinx.android.extensions.LayoutContainer 。它仍然是一项实验性功能,因此您必须启用它:

androidExtensions {
    experimental = true
}

然后你必须直接在实例上调用合成属性。每次调用这些作为 View 的 属性 都会导致未缓存的调用。

因此,您应该直接使用 my_text_viewmy_another_view,而不是使用 ontainerView.my_text_viewitemView.my_another_view

因此,使用任何 kotlinx.android.synthetic.main.activity_main.view.* 都会导致对 findViewById().

的未缓存调用