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?
ViewHolder class which caches views associated with the default Preference layouts. A ViewHolder describes an item view and metadata about its place within the RecyclerView. Adapter implementations should subclass ViewHolder and add fields for caching potentially expensive View#findViewById(int) results.
findViewById. Recently Android has announced that with Kotlin 1.4. 20, their Android Kotlin Extensions Gradle plugin will be deprecated and will no longer be shipped in the future Kotlin releases.
Kotlin Android Extensions is deprecated, which means that using Kotlin synthetics for view binding is no longer supported.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With