Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

android - kotlin - How synthetic property initialise view?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...