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.
[sourcecode lang=”xml” highlight=”6″]
<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>
[/sourcecode]
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
[sourcecode lang=”java”]
TextView textView = (TextView) findViewById(R.id.textView1);
[/sourcecode]
Now, with your [cci]TextView[/cci] in hand, you can set text to it as you want like this
[sourcecode lang=”java”]
if(textView != null) textView.setText("new text");
[/sourcecode]
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].
[sourcecode lang=”xml” highlight=”14″]
<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"/>
[/sourcecode]
0 Comments