本文介绍了kotlin-综合资产如何初始化视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在代码中使用了合成属性.但是想知道它如何以及何时实际初始化android中的每个视图.

I used synthetic property in my code.But wondering for how and when it actually initialise each view in android.

我们只提供导入并通过其ID访问每个视图.它何时为视图对象分配内存?

We simply provide import and access each view by its id. When it allocate memory for view object?

推荐答案

通过在使用Kotlin Android扩展程序的地方反编译Kotlin文件,这很容易进行调查. (您可以执行以下操作:转到Tools -> Kotlin -> Show Kotlin Bytecode,然后在出现的窗格中选择Decompile.)简而言之,这没什么神奇的,它只使用findViewById然后将View强制转换为具体类型.

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.

如果在ActivityFragment中使用它,它们将被缓存在Map中,因此查找仅发生一次.之后,您只需支付以ID作为键来获取地图条目的费用.

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.

您也可以在ViewGroup上使用它来查找其中具有给定ID的子级,在这种情况下,没有缓存,这些调用将被简单的findViewById调用所取代,每次调用该行时都会发生到达.第二种语法如下所示:

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");


请注意,膨胀版式时仍会创建实际的View实例. Kotlin Android扩展仅是findViewById调用上的语法糖.


Note that the actual View instances are still created when your layout is inflated. Kotlin Android Extensions is only syntactic sugar over findViewById calls.

这篇关于kotlin-综合资产如何初始化视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:55