How can I use duplicate IDs in different layouts? How can I use duplicate IDs in different layouts? android android

How can I use duplicate IDs in different layouts?


On the "Duplicate Ids in layouts" topic, extracted from android developers

Defining IDs for view objects is important when creating a RelativeLayout. In a relative layout, sibling views can define their layout relative to another sibling view, which is referenced by the unique ID.

An ID need not be unique throughout the entire tree, but it should be unique within the part of the tree you are searching (which may often be the entire tree, so it's best to be completely unique when possible).

Which means different layouts may declare identical IDs, tho it's not a best practice.


I imagine there would be an issue in the R.java class, as this class will have public static members corresponding to each View id.

For it to work, the R.java class would need to rename some of those id's, and then how would you find them?


You can have the same IDs but it should be in different layouts. The same layout cannot handle duplicate IDs. I have taken two layouts as you did containing buttons having as "btn". I am calling the Activity2 having newxml.xml from the Activity1 having main.xml.

Here is my code:

main.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <Button        android:id="@+id/btn"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Next" /></LinearLayout>

Activity1:

setContentView(R.layout.main);Button button=(Button) findViewById(R.id.btn);button.setOnClickListener(new OnClickListener() {        @Override        public void onClick(View v) {            Intent intent=new Intent(Activity1.this,Activity2.class);            startActivity(intent);        }    });

newxml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <Button         android:id="@+id/btn"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Previous"/></LinearLayout>

Activity2:

setContentView(R.layout.newxml);Button button=(Button) findViewById(R.id.btn);button.setOnClickListener(new OnClickListener() {    @Override    public void onClick(View v) {        finish();    }});