在ViewHolder中使用kotlin-android-extensions

class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bindata(text: SingleText){ itemView.title.text = text.title itemView.desc.text = text.desc } } 

像这样的代码,Kotlin在android扩展中有任何缓存?

当我反编译Kotlin字节码

 public final void bindata(@NotNull SingleText text) { Intrinsics.checkParameterIsNotNull(text, "text"); ((AppCompatTextView)this.itemView.findViewById(id.title)).setText((CharSequence)text.getTitle()); ((AppCompatTextView)this.itemView.findViewById(id.desc)).setText((CharSequence)text.getDesc()); } 

这意味着当我在Adapter.onBindViewHolder()中调用binData时,它会每次调用findViewById

这大大增加了性能的损失,并没有达到布局重用的目的

Kotlin在ViewHolder的android扩展中有任何缓存逻辑?

ViewHolder或任何自定义类中查看缓存只能从Kotlin 1.1.4开始 ,目前处于实验阶段。

  1. 在根级build.gradle文件中更新您的Kotlin版本

classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.4-3"

  1. 在您的应用程序build.gradle添加这些行:

androidExtensions { experimental = true }

  1. LayoutContainer继承ViewHolder类。 LayoutContainerkotlinx.android.extensions包中的一个可用接口。

  2. 添加下面的导入,其中view_item是布局名称。

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

整个ViewHolder类看起来像:

 class ViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer { fun bind(title: String) { itemTitle.text = "Hello Kotlin!" // itemTitle is the id of the TextView in the layout } } 

反编译的Java代码显示这个类为视图使用缓存:

  public final void bind(@NotNull String title) { Intrinsics.checkParameterIsNotNull(title, "title"); ((TextView)this._$_findCachedViewById(id.itemTitle)).setText((CharSequence)"Hello Kotlin!"); } 

进一步阅读: 保持提案 , 一个真棒教程 。

从我的理解,kotlin-android-extensions只是一个静态导入的扩展(生成的代码)来取代View.findViewById。

我建议您将参考文献存储在您的查看者中。

 class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val title: TextView = itemView.title val desc: TextView = itemView.desc fun bindata(text: SingleText){ title.text = text.title desc.text = text.desc } } 

这种方法的好处之一是在编译时会发现任何类型的不匹配!