Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if I use the same id for several widgets in different layouts?

Tags:

android

layout

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.

Thanks

like image 815
lost baby Avatar asked Nov 11 '10 14:11

lost baby


2 Answers

Yes, you can use the same ids in different layouts. In fact, it may be good practice to.

like image 78
jamesh Avatar answered Nov 10 '22 02:11

jamesh


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.

like image 25
mxcl Avatar answered Nov 10 '22 04:11

mxcl