Ankit Ankit - 1 month ago 14
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 R.java
For instance, if we have same IDs, say "image1" in two XMLs, say "layout1" & "layout2". but in R.java 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?

Answer

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.

http://developer.android.com/guide/topics/ui/declaring-layout.html

Example

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button myButton = (Button) findViewById(R.id.my_button);
 }

Xml

  <Button android:id="@+id/my_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/my_button_text"/>  

Here

  Button myButton = (Button) findViewById(R.id.my_button);

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

Open your R.java do not modify its content. R.java 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 R.id.my_button.

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.