Wer*_*erb 14 android adapter kotlin android-recyclerview kotlin-android-extensions
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindata(text: SingleText){
itemView.title.text = text.title
itemView.desc.text = text.desc
}
}
Run Code Online (Sandbox Code Playgroud)
像这个代码一样,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());
}
Run Code Online (Sandbox Code Playgroud)
这意味着当我在Adapter.onBindViewHolder()中调用binData时,它每次都会调用findViewById
这显着增加了性能损失,并且它没有达到布局重用的目的
Kotlin在ViewHolder的android扩展中有任何缓存逻辑吗?
Bob*_*Bob 29
ViewHolder只能从Kotlin 1.1.4中查看一个或任何自定义类中的缓存,并且它目前处于试验阶段.
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.4-3"
build.gradle:androidExtensions {
experimental = true
}
继承你的ViewHolder班级LayoutContainer.LayoutContainer是一个kotlinx.android.extensions包中可用的接口.
添加以下导入,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
}
}
Run Code Online (Sandbox Code Playgroud)
反编译的Java代码显示此类使用视图的缓存:
public final void bind(@NotNull String title) {
Intrinsics.checkParameterIsNotNull(title, "title");
((TextView)this._$_findCachedViewById(id.itemTitle)).setText((CharSequence)"Hello Kotlin!");
}
Run Code Online (Sandbox Code Playgroud)
Gar*_* LO 10
根据我的理解,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
}
}
Run Code Online (Sandbox Code Playgroud)
这种方法的好处之一是在编译时会发现任何类型不匹配!