Ankit Ankit - 7 months ago 39
Android Question

how does multiple component with same id work in android?

I have defined several layouts, where few id's are multiple defined. I am confused how does it work? why doesn't it give error just like we get in java code? and most importantly, how does environment decide to which component it needs to invoke?

I understand the process of id generation is automated, which gets added to
For instance, if we have same IDs, say "image1" in two XMLs, say "layout1" & "layout2". but in it won't have 2 IDs. that means at a time it will reference only 1 component.

In case we have to use 2 XMLs in an Activity, one as activity.setcontentview(layout1) and another as a PopupWindow.setContentView(layout2). What will happen in such case?

may be its pretty basic question but am I missing something?


You can findViewById of the current view hierarchy set to the activity. You cannot have same id for the view's in the same view tree. (must be unique).

Quoting from the docs

Any View object may have an integer ID associated with it, to uniquely identify the View within the tree. When the application is compiled, this ID is referenced as an integer, but the ID is typically assigned in the layout XML file as a string, in the id attribute. This is an XML attribute common to all View objects (defined by the View class) and you will use it very often.


public void onCreate(Bundle savedInstanceState) {
    Button myButton = (Button) findViewById(;


  <Button android:id="@+id/my_button"


  Button myButton = (Button) findViewById(;

findViewById is the method is an int value. Will have an entry in which is auto generated. Here under the same xml file under the current view tree you cannot have views with same id.

Open your do not modify its content. will look something like below

  public static final class id {
      public static final int my_button=0x7f080004; // this is the int value which is unique

In onCreate you refer like

You can have ids same in different xml files because whenever you use findViewById() to get a reference to a part of your layout, the method only looks for that view in the currently inflated layout. (current view tree/hierarchy).

But it is better have ids unique to avoid confusion.