Android:具有相同 ID 的元素的不同布局 - 有效,但为什么?
今晚我正在开发一个应用程序,我注意到我有两个类似的活动,它们具有不同的布局(mylayout1.xml 和 mylayout2.xml)...但在这些布局中,我有一些相同的元素,直到它们的 id (每个布局文件中的“@+id/mybutton”)。
当我在活动中 setContentView(R.layout.mylayout1) 然后 findViewById(R.id.mybutton) 执行 setOnClickListener() 时,当我最终单击它时,Android 如何“知道”我真正指的是哪个按钮?
一切似乎都工作得很好,触发了适当的回调(据我所知,没有进入错误的活动 - 尽管到目前为止,在我的测试中一次只有一个在屏幕上(例如,对话框类型)我只是突然想到(因为我在不相关的工作中注意到了这种重复),也许这只是偶然而不是设计,如果 Android 对此很聪明,我就不会担心。此类元素的一个实例永远不会出现在屏幕上同时(例如“确定”按钮)。
I was working on an app tonight and I noticed that I have two similar activities which have different layouts (mylayout1.xml and mylayout2.xml)... but within those layouts I have some elements that are identical, right down to their ids ("@+id/mybutton" in each layout file).
When I setContentView(R.layout.mylayout1) in an activity and then findViewById(R.id.mybutton) to perform setOnClickListener(), how does Android "know" which button I'm really referring to when I finally click it?
Everything seems to work just fine, with the appropriate callbacks triggering (and not, so far as I can tell, going to the wrong activity - though only one is on-screen at a time in my tests so far (e.g., dialog-type activities). It just occurs to me (as I noticed this duplication during unrelated work) that maybe this is working simply by chance rather than design. OTOH, if Android is being smart about it, I won't worry as long as more than one instance of such an element is never on-screen at the same time (such as OK buttons).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您调用 setContentView 时,将解析并创建 XML 中的视图层次结构。然后,当您搜索具有特定 id 的视图时,android 将查看该视图层次结构并搜索具有匹配 id 的视图。因此,您永远不会得到在其他 .xml 文件中定义的具有相同 id 的视图元素,因为这些视图元素不是活动视图层次结构的一部分。
When you are calling setContentView the view hierarchy from XML is parsed and created. When you then search for a View with a specific id android will look into that view hierarchy and search for a view with that matching id. So you will never end up with a view element which is defined in some other .xml file with the same id because these view elements are not part of the activities view hierarchy.
这是因为 setContentView(View) 方法将活动内容设置为显式视图(如文档中所示),而 finbViewById(int id) 引用您使用 setContentView 设置的视图对象。事实上,如果您引用布局中未正确设置的元素,应用程序将因空指针异常而崩溃......
That's because the setContentView(View) method sets, as stands int the doc, the activity content to an explicit view, and finbViewById(int id) refers to the view object you set with setContentView. As matter of fact, if you refer an element in a layout that you do not properly set, the application crash with null pointer exception...