kotlin - How synthetic property initialise view?

本秂侑毒 提交于 2019-12-13 09:09:45

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/45073956/kotlin-how-synthetic-property-initialise-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!