Open main menu

CDOT Wiki β

Changes

MAP524/DPS924 Lecture 3

35 bytes added, 18:01, 18 July 2015
IDs
IDs are used as a way to connect the elements defined in XML with your java source code. In XML for nearly every element you can specify an "id" attribute. For exmaple:
<presource lang="xml"><Button android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/my_button_text"/></presource>
You will rarely if ever change the "@+id/" prefix, but after the slash you can set whatever ID you like. Normally you want something that will describe what that element is and does, for example "sendEmailNowBtn". Otherwise your code will be harder to read ("what my_button, they're all my buttons).
To get a reference to the button in your Java code you use findViewById() with a cast. In this example:
<presource lang="java">Button myButton = (Button) findViewById(R.id.my_button);</presource>
findViewById looks up the element by ID (my_button). Remember the R class is automatically generated based on your XML files.
The return is a View, but we know it's a button so we'll cast it to Button. Without a case you'd only be able to use te View methods on the button. Button is obviously a subclass of View.