You can findViewById
of the current view hierarchy set to the activity. You cannot have same id for the view's in the same view tree. (must be unique).
Quoting from the docs
Any View object may have an integer ID associated with it, to uniquely identify the View within the tree. When the application is compiled, this ID is referenced as an integer, but the ID is typically assigned in the layout XML file as a string, in the id attribute. This is an XML attribute common to all View objects (defined by the View class) and you will use it very often.
http://developer.android.com/guide/topics/ui/declaring-layout.html
Example
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button myButton = (Button) findViewById(R.id.my_button);
}
Xml
<Button android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/my_button_text"/>
Here
Button myButton = (Button) findViewById(R.id.my_button);
findViewById
is the method R.id.button
is an int value. Will have an entry in R.java which is auto generated. Here under the same xml file under the current view tree you cannot have views with same id.
Open your R.java do not modify its content. R.java will look something like below
public static final class id {
public static final int my_button=0x7f080004; // this is the int value which is unique
}
In onCreate
you refer like R.id.my_button
.
You can have ids same in different xml files because whenever you use findViewById()
to get a reference to a part of your layout, the method only looks for that view in the currently inflated layout. (current view tree/hierarchy).
But it is better have ids unique to avoid confusion.