简体   繁体   English

具有相同ID的两个视图

[英]two views with same id

How does android use R.id.id_name to find views after inflating the XML? 膨胀XML后,android如何使用R.id.id_name查找视图?

1.Suppose I have two XML's with one button each with same id. 1.假设我有两个带有一个按钮的XML,每个按钮具有相同的ID。

2.I have inflated them and converted them into views 2.我夸大了它们并将它们转换为视图

3.In R.id class only one int will be created for both the buttons. 3.在R.id类中,两个按钮都只会创建一个int

How does android differentiate these buttons with same id Using same Resource name(R.id.id_name) . android如何使用相同的Resource name(R.id.id_name)区分具有相同id的这些按钮。

The ID is not a unique reference. 该ID不是唯一参考。

However, in practice, you differentiate by using the parent view. 但是,实际上,您可以通过使用父视图来区分。

If we consider that 'this' is an Activity, set up with a layout that contains your buttons, then: 如果我们认为“这”是一个活动,请设置包含您的按钮的布局,然后:

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

will return the first one it finds in the layout (I think - not sure the actual behaviour is defined). 将返回它在布局中找到的第一个(我想-不确定是否定义了实际行为)。

However what you might do is call findViewById on some parent view that contains only one such instance with that ID. 但是,您可能要做的是在某些仅包含一个具有该ID的实例的父视图上调用findViewById

LinearLayout okParent = (LinearLayout) this.findViewById( R.id.okLayout );
LinearLayout cancelParent = (LinearLayout) this.findViewById( R.id.cancelLayout );

Button okButton = (Button) okParent.findViewById( R.id.id_name );
Button cancelButton = (Button) cancelParent.findViewById( R.id.id_name );

Conceptually, this is a sort of path based lookup. 从概念上讲,这是一种基于路径的查找。 You should be careful to design your layouts such that this is possible. 您应该谨慎设计布局,以使这成为可能。

Android takes the easy road: IDs are not application-wide unique, but layout-wide unique. Android走上了一条轻松之路: ID并不是应用程序范围内唯一,而是布局范围内唯一。

The value of R.id.foo is the same across two different layouts holding a control with foo id. R.id.foo的值在两个具有foo id的控件的不同布局中是相同的。 Since they are not competing for uniqueness, it doesn't matter. 由于他们不竞争唯一性,所以没关系。

它知道应该使用哪个View ,因为它会在当前设置为内容视图(或已充气)的XML文件中查找具有此特定id View

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM