3

Kotlin Android 扩展允许我们访问布局 XML 中的视图,就像它们是属性一样,使用您在布局定义中使用的 id 的名称。为此,它构建了一个本地视图缓存。

但是有了RecycleView适配器,我们就失去了这种可能性。

我知道使用 Kotlin Android Extensions 1.1.4 解决方案是通过LayoutContainer接口解决的。但问题不在于这个。

我的问题是为什么 Kotlin Android Extensions 插件无法使用ViewHolder视图创建视图缓存?是什么原因?我可以提供适当的合成导入,例如:

kotlinx.android.synthetic.main.view_item.view.*

为什么不能用这个导入的视图生成视图缓存?

4

2 回答 2

1

不幸的是,我匆忙提出这个问题。我自己找到了答案,但也许有人会派上用场。答案在 Kotlin 字节码中。

这是_$_findCachedViewById使用 Kotlin Android Extensions 插件为活动生成的:

public View _$_findCachedViewById(int var1) {
  if (this._$_findViewCache == null) {
     this._$_findViewCache = new HashMap();
  }

  View var2 = (View)this._$_findViewCache.get(var1);
  if (var2 == null) {
     var2 = this.findViewById(var1); // this is an Activity reference
     this._$_findViewCache.put(var1, var2);
  }

  return var2;

}

这是为该实现接口_$_findCachedViewById生成的:ViewHolderLayoutContainer

public View _$_findCachedViewById(int var1) {
  if (this._$_findViewCache == null) {
    this._$_findViewCache = new HashMap();
  }

  View var2 = (View)this._$_findViewCache.get(var1);
    if (var2 == null) {
      View var10000 = this.getContainerView();
      if (var10000 == null) {
        return null;
      }

      var2 = var10000.findViewById(var1); // var2 is a сontainerView reference
      this._$_findViewCache.put(var1, var2);
    }

    return var2;
}

如果扩展插件创建缓存Activity或者Fragment它使用它们的引用来通过 id 查找视图。使用ViewHolder该实现LayoutContainer接口,它使用containerView参考来查找视图。但是,ViewHolder如果没有LayoutContainerKotlin 扩展插件,现在不会使用哪个参考来查找视图。

于 2018-07-20T13:38:28.550 回答
0

你读过扩展保持吗?

如果没有显式LayoutContainer接口,您可以在给定视图中找到视图 - 但扩展本身不知道在哪里存储缓存。

于 2018-07-20T13:35:10.207 回答