If I have a simple custom view:
myitem.xml
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<FrameLayout/>
Accessing a kotlinx syntentic property:
import kotlinx.android.synthetic.main.myitem.view.*
view.toolbar.text = "Some text"
Internally it generates a call to findByViewID()
. So my question is:
Is the result cached for custom views like for activities or each each time findByViewID
is called? The answer is quite important for performance reasons.
Kotlin Android Extensions: What’s this? Kotlin Android Extensions are another Kotlin plugin that is included in the regular one, and that will allow recovering views from Activities, Fragments, and Views in an amazing seamless way.
Kotlin Android Extensions are deprecated, you should start using View Binding. If you’ve been developing Android Apps for some time, you’re probably already tired of working with findViewById in your day-to-day life to recover views. Or maybe you gave up and started using the famous Butterknife library.
yes. the code is generated (the map and the cache function are there). But accessing a property via syntehetic is translated into findViewById byte code (i see it through the 'Kotlin Bytecode' option) – johnny_crq
In Android, if you want to change the properties of views from your layout, like changing the text of a TextView or adding an onClickListener , you would have to first assign that view’s id to a variable by calling findViewById . For example, if you only had one TextView with an id of textView, you’d need to write the following Kotlin code:
Since 1.1.4 views can be cached in any class.
Caching in custom views enabled by default. For ViewHolders you need to implement LayoutContainer
interface like this:
class MyViewHolder(override val containerView: View): LayoutContainer
See this doc for details https://github.com/Kotlin/KEEP/blob/master/proposals/android-extensions-entity-caching.md
Update:
To be able to use LayoutContainer
you should add this to the gradle script:
androidExtensions {
experimental = true
}
In the current version (1.1.3), views are cached for Activities and Fragments layouts. For other kinds of containers like RecyclerView ViewHolders, there is no cache.
Also, the cache is a HashMap
with Integer boxing for keys. A SparseArray
would have been better.
Edit: Since version 1.1.4, views can be cached for other classes too, including ViewHolder
, if you make them implement the LayoutContainer
interface. You can also use the @ContainerOptions
annotation to specify another cache implementation, including SparseArray
. Both of these features are still experimental and need to be enabled manually in your build.gradle
file:
androidExtensions {
experimental = true
}
Read more about it.
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