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

I am currently trying to use different identifiers for each widget, but if I used the same identifier for some widgets in different layout XML files, what would happen to my findViewById calls? Will it be confusing and return the widget from the wrong layout file?

I ask because I was thinking about turning on the view (with several buttons) in some other views, then each of these screen classes would have to assign a slightly different behavior to each button of the included view. But for this, they will call findViewById on the same identifier. For example, currently I like this in every 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 modify R.id in each file to indicate a widget in each approved layout. it would be nice if I could use one R.id for everyone, so I don’t need to customize every layout file and every screen class.

thanks

+6
android layout
source share
3 answers

This should be good if you do not instantiate both layouts in the same action. But, never tried, I would not want to guarantee this.

However, I won’t be surprised if an Android code generator is detected, although it will probably try to create two R.id.rshome_button entries in your R.java file.

+3
source share

Yes, you can use the same id in different layouts. This may actually be good practice.

+8
source share

The best way to try it yourself.

But you are using setContentView (R.layout.your_layout);

So, if you call findViewById, it will look for the widget with the given id in your_layout

This is why you can use the same identifier in different layouts.

-one
source share