如何findViewById初始化一个视​​图 [英] How does findViewById initialise a view

查看:90
本文介绍了如何findViewById初始化一个视​​图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是写了一个答案的人蛊惑findViewById,我意识到,我在我的理解的差距。这个问题是知识,只有好奇。

I just wrote an answer for someone confused by findViewById and I realised that I have a gap in my understanding. This question is for knowledge and curiosity only.

考虑一下:

button = (Button)findViewById(R.id.button);

findViewById 返回查看,然后将其转换为目标类的一个实例。所有好为止。

findViewById returns an instance of View, which is then cast to the target class. All good so far.

要设置视图, findViewById 构造一个的AttributeSet 从它传递给相关的XML声明的参数的构造查看

To setup the view, findViewById constructs an AttributeSet from the parameters in the associated XML declaration which it passes to the constructor of View.

我们再铸造查看实例按钮

如何在的AttributeSet 又到按钮获得通过的构造函数?

How does the AttributeSet get passed in turn to the Button constructor?

所以,我是糊涂的:)。整点是,当布局膨胀,视图层次结构中已包含该视图子类的实例。 findViewById只是返回一个引用。明显,当你想想看 - 卫生署..

So I was the confused one :). The whole point is that when the layout is inflated, the view hierarchy already contains an instance of the view descendant class. findViewById simply returns a reference to it. Obvious when you think about it - doh..

推荐答案

findViewById 什么都不做。它只是看起来通过视图层次并返回引用与要求的ViewID 视图。 查看已创建和存在。如果你不叫 findViewById 一些看法没有改变。

findViewById does nothing. It just looks through view hierarchy and returns reference to a view with requested viewId. View is already created and exists. If you do not call findViewById for some view nothing changes.

视图是由 LayoutInflator 充气。当你调用的setContentView XML布局进行解析,并创建视图层次结构。

Views are inflated by LayoutInflator. When you call setContentView xml layout is parsed and view hierarchy is created.

LayoutInflater 传递给巴顿的构造属性。检查<一href="http://grep$c$c.com/file/repository.grep$c$c.com/java/ext/com.google.android/android/2.2_r1.1/android/view/LayoutInflater.java#LayoutInflater.inflate%28org.xmlpull.v1.XmlPullParser,android.view.ViewGroup,boolean%29"相对=nofollow> LayoutInflator源$ C ​​$ C 。

attributes passed to Button's constructor by LayoutInflater. check LayoutInflator source code.

这篇关于如何findViewById初始化一个视​​图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆