I had the same doubts. In my situation, I have a main layout and an additional layout (inside the main one) - two were RelativeLayout - and I want to get the components that I added on the screen.
But I had to use dynamic keys (which could be repeated) and were the only parameter that I could use to identify components.
Like Natali, in her answer , I use βTAGβ in components and worked for me. See below (using the button as an example):
Step 1: Declare a button type variable. Button btn = new Button(this) ; // this is the context of my activity
Step 2: Install any key. String any_key = "keyToGetButton";
Step 3: Install the tag (the key installed in step 2) on your button. btn.setTag(any_key);
Step 4: Get your button by tag (for example, in another way). Button button = (Button) your_layout_where_is_button.findViewWithTag(any_key);
source share