I used synthetic property in my code.But wondering for how and when it actually initialise each view in android.
We simply provide import and access each view by its id. When it allocate memory for view object?
I used synthetic property in my code.But wondering for how and when it actually initialise each view in android.
We simply provide import and access each view by its id. When it allocate memory for view object?
This is easy enough to investigate by decompiling a Kotlin file where you use Kotlin Android Extensions. (You can do this by going to Tools -> Kotlin -> Show Kotlin Bytecode
and then choosing Decompile
in the pane that appears.) In short, it's nothing magical, it just uses findViewById
and then casts the View
to the concrete type for you.
If you use it inside an Activity
or a Fragment
, these get cached in a Map
so that the lookup only occurs once. After that, you're only paying the costs of fetching a map entry by the ID as the key.
You can also use it on a ViewGroup
to find a child with a given ID in it, in these cases, there's no caching, these calls are replaced by simple findViewById
calls that will happen every time that line is reached. This second syntax looks something like this:
val view = inflater.inflate(...)
view.btnLogin.text = "Login"
And it will translate to something similar to this in the bytecode:
View view = inflater.inflate(...);
Button btnLogin = (Button) view.findViewById(R.id.btnLogin);
btnLogin.setText("Login");
Note that the actual View
instances are still created when your layout is inflated. Kotlin Android Extensions is only syntactic sugar over findViewById
calls.