35

How does android use R.id.id_name to find views after inflating the XML?

1.Suppose I have two XML's with one button each with same id.

2.I have inflated them and converted them into views

3.In R.id class only one int will be created for both the buttons.

How does android differentiate these buttons with same id Using same Resource name(R.id.id_name) .

tez
  • 4,990
  • 12
  • 47
  • 67
  • Related post - [Can I use the same id in different layout in Android?](https://stackoverflow.com/q/12333624/465053) – RBT Aug 19 '18 at 09:03

3 Answers3

45

The ID is not a unique reference.

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.

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.

Rob Pridham
  • 4,780
  • 1
  • 26
  • 38
  • 1
    That's why its ID (short for Identifier) & not UID (Unique Identifier). There are UUIDs too which mean Universally Unique Identifiers. – Amit Kumar May 23 '21 at 14:21
23

Android takes the easy road: IDs are not application-wide unique, but layout-wide unique.

The value of R.id.foo is the same across two different layouts holding a control with foo id. Since they are not competing for uniqueness, it doesn't matter.

salezica
  • 74,081
  • 25
  • 105
  • 166
7

It knows which View should it use, because it looks for View with this specific id in a XML file that is currently set as content view (or is inflated).

Piotr Chojnacki
  • 6,837
  • 5
  • 34
  • 65