What happens if I use the same ID for multiple widgets in different layouts?


Currently I am careful to use different IDs for each widget, but if I used the same id for some widgets in different layout xml files, what would happen to my calls to findViewById? Would it get confused and return a widget from the wrong layout file?

I ask because I was thinking of including a view (with a row of buttons) in some other views, then each of those screen classes would have to assign a slightly different behavior to each button on the included view. But to do that they would be calling findViewById on the same id. For instance currently I do like this in each file:

final ImageButton homeButton = (ImageButton)this.findViewById(R.id.rshome_button);
homeButton.setOnClickListener(new BottomButtonClickListener());

final ImageButton hotButton = (ImageButton)this.findViewById(R.id.rshotlist_button);
hotButton.setOnClickListener(new BottomButtonClickListener());

final ImageButton locButton = (ImageButton)this.findViewById(R.id.rsbot_map);
locButton.setOnClickListener(new BottomButtonClickListener());

final ImageButton sendButton = (ImageButton)this.findViewById(R.id.rssend_button);
sendButton.setOnClickListener(new BottomButtonClickListener());

But I change the R.id in each file to point to the widget in each assiciated layout. it would be nice if I could use the one R.id for all so I don't have to tweak every layout file and every screen class.


It should be fine as long as you don't instantiate both layouts in the same activity. But having never tried it I wouldn't like to guarantee it.

However, I wouldn't be surprised if the Android code generator errors out though, as it will probably try to create two R.id.rshome_button entries in your R.java file.