class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindata(text: SingleText){
itemView.title.text = text.title
itemView.desc.text = text.desc
}
}
like this code, Kotlin has any cache in android-extensions?
when i decompile kotlin bytecode
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());
}
it means when i called binData in Adapter.onBindViewHolder(), it will called findViewById each time
This significantly increases the loss of performance,and It does not achieve the purpose of layout reuse
Kotlin has any cache logic in android-extensions with ViewHolder?
View caching in a ViewHolder
or any custom class is possible only from Kotlin 1.1.4 and it's currently in the experimental stage.
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.4-3"
build.gradle
:androidExtensions {
experimental = true
}
Inherit your ViewHolder
class from LayoutContainer
. LayoutContainer
is an interface available in kotlinx.android.extensions
package.
Add the below imports, where view_item
is the layout name.
import kotlinx.android.synthetic.main.view_item.*
import kotlinx.android.synthetic.main.view_item.view.*
The entire ViewHolder
class looks like:
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
}
}
The decompiled Java code shows that this class uses cache for the Views:
public final void bind(@NotNull String title) {
Intrinsics.checkParameterIsNotNull(title, "title");
((TextView)this._$_findCachedViewById(id.itemTitle)).setText((CharSequence)"Hello Kotlin!");
}
Further readings: KEEP proposal, an awesome tutorial.