Give an ID to your view object is very useful if you want to refer to that view later in source code. For example you want to set text of a TextView in source code. To do that, put [cci]android:id[/cci] attibute to your view.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout>
In above code, you can see I have put an [cci]android:id=”@+id/textView1″[/cci]. This line defines an [cci]id[/cci] of our [cci]TextView[/cci] to [cci]textView1[/cci].
Refers view from activity
After you have defined an id, now you can refer to your [cci]TextView[/cci] in an activity like this
TextView textView = (TextView) findViewById(R.id.textView1);
Now, with your [cci]TextView[/cci] in hand, you can set text to it as you want like this
if(textView != null) textView.setText("new text");
Refers view in xml file
Sometimes we need to refers to our view in the xml layout file. For example you want to align top another [cci]TextView[/cci] to other. To achieve this, you can refer to our last [cci]TextView[/cci] like this [cci]@id/textView1[/cci]. Note you must replace ‘+’ sign when referring to already defined [cci]id[/cci]. Use ‘+’ sign only in first time when you define an [cci]id[/cci].
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@id/textView1"/>