Search code examples
javaandroidandroid-studioandroid-4.2-jelly-bean

Telling the Difference between two Android GUI objects with the same ID


Say we have two XML files, of which these are snippets:

firstxml.xml

<?xml version="1.0" encoding="utf-8"?>
<Button
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:id="@+id/button1 />

secondxml.xml

<?xml version="1.0" encoding="utf-8"?>
<Button
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:id="@+id/button1 />

In our onCreate() method:

//Assume all packages necessary are imported
public class Example
{
    public void onCreate(Bundle sis)
    {
      super.onCreate(sis);
      setContentView(R.layout.firstxml);

      Button thisButton = (Button) findViewbyId(R.id.button1);

    }
}

Which button is called and instantiated when this code runs? Since the two buttons are in two different files, will the button in firstxml.xml be called because it is the content view of the function?

Thanks in advance for your answers!


Solution

  • You are referencing the the first XML layout file R.layout.firstxml in the activity's onCreate(Bundle...) method, so the search here will be made.

    Any call to findViewById(int id); will search in your inflated layout R.layout.firstxml.

    The R.java file is automatically generated when you are defining/adding a new view to your layout.

    You can use the same id multiple times, but not in the same layout !