I was working on an app tonight and I noticed that I have two similar activities which have different layouts (mylayout1.xml and mylayout2.xml)… but within those layouts I have some elements that are identical, right down to their ids (“@+id/mybutton” in each layout file).
When I setContentView(R.layout.mylayout1) in an activity and then findViewById(R.id.mybutton) to perform setOnClickListener(), how does Android “know” which button I’m really referring to when I finally click it?
Everything seems to work just fine, with the appropriate callbacks triggering (and not, so far as I can tell, going to the wrong activity – though only one is on-screen at a time in my tests so far (e.g., dialog-type activities). It just occurs to me (as I noticed this duplication during unrelated work) that maybe this is working simply by chance rather than design. OTOH, if Android is being smart about it, I won’t worry as long as more than one instance of such an element is never on-screen at the same time (such as OK buttons).
When you are calling setContentView the view hierarchy from XML is parsed and created. When you then search for a View with a specific id android will look into that view hierarchy and search for a view with that matching id. So you will never end up with a view element which is defined in some other .xml file with the same id because these view elements are not part of the activities view hierarchy.