3

Kotlin Android Extensions allow us to access views in the layout XML just as if they were properties, with the name of the id you used in the layout definition. It builds a local view cache for this purpose.

But with the RecycleView adapter we loose this possibility.

I know that with Kotlin Android Extensions 1.1.4 the solution is solved with LayoutContainer interface. But question is not about this.

My question is why it is not possible for Kotlin Android Extensions plugin to create view cache with ViewHolder view? What is the reason? I can provide proper synthetic import, for example:

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

Why it's not possible to generate view cache with this imported view?

bitvale
  • 1,959
  • 1
  • 20
  • 27

2 Answers2

1

Unfortunately I hurried with the question. I found answer by myself, but maybe someone will come in handy. Answer is in Kotlin Bytecode.

This is _$_findCachedViewById generated with Kotlin Android Extensions plugin for Activities:

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;

}

This is _$_findCachedViewById generated for ViewHolder that implement LayoutContainer interface:

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;
}

If the extensions plugin create cache for Activity or Fragment it use their references for finding views by id. With ViewHolder that implement LayoutContainer interface it use containerView reference for finding views. BUT with ViewHolder without LayoutContainer the Kotlin Extension Plugin does not now which reference to use for finding views.

bitvale
  • 1,959
  • 1
  • 20
  • 27
0

Have you read extension keep?

Without explicit LayoutContainer interface you can find view within a given view - but extension itself has no idea where to store the cache.

Pawel
  • 15,548
  • 3
  • 36
  • 36